tags:

views:

22

answers:

3

I have this:

$(window).blur(function() {
    setInterval(function() {
        $.ajax({
            type: "POST",
            url: "imback.php",
            data: {
                mode: 'ajax',
                getUpdates: 'auto',
            },
            success: function(msg){
                document.title = msg + titleOrig;
            }
        });
    }, 35000);

Works fine.

Although, if you have been blur, and then when you focus back, it will keep making the ajax call, it doesnt stop sending ajax call after interval 35 seconds.

How can i fix this? })

A: 

Looks like you need to clearInterval() on focus

wdavis
+1  A: 

You need to store the interval when you set it, and then clear it on window focus. Like this:

var interval = null;

$(window).blur(function() {
    if (interval) clearInterval(interval);
    interval = setInterval(function() {
        $.ajax({
            type: "POST",
            url: "imback.php",
            data: {
                mode: 'ajax',
                getUpdates: 'auto',
            },
            success: function(msg){
                document.title = msg + titleOrig;
            }
        });
    }, 35000);
});

$(window).focus(function() {
    if (interval) clearInterval(interval);
    interval = null;
});
Ben Lee
A: 

Using a closure:

$(window).blur(function() {
    tracktime = new Date();
    var iVal = setInterval(function() {
        $.ajax({
            type: "POST",
            url: "imback.php",
            data: {
                mode: 'ajax',
                getUpdates: 'auto',
            },
            success: function(msg){
                document.title = msg + titleOrig;
            }
        });
    }, 2000);

    $(window).focus(function() { clearInterval(iVal); });
});

This allows you to not have to check if you've set the Interval before clearing it. And, it lets you ensure you're clearing the correct Interval instead of hoping no other call has overwritten your variable.

palswim