Utku Dalmaz
Utku Dalmaz

Reputation: 10162

setInterval stops without any reason when browser tab is background

I am working on an application that sends current timestamp to database every 2 minutes with AJAX using setInterval.

But somehow setInterval stops after some minutes (i didnt calculate the exact time), but i believe it happens when i dont open that browser's tab for 20-30 minutes.

function tmstmp() {
$.post("send_functions.php?act=time");
}

$(function() { 
setInterval(tmstmp, 60000);
});

Is that normal that setInterval stops if that tab is not on foreground ?

If yes, how can i prevent setInterval to stop ? or check if it stopped ?

Thanks

Upvotes: 1

Views: 8667

Answers (3)

Jakub
Jakub

Reputation: 21

You should try to make an function call on page startup:

test();

and then loop that function:

function test() {
    setTimeout(function() {
        // your code
        test();
    }, 2000);
}

Upvotes: 2

user188654
user188654

Reputation:

No code + no debug information = hard to tell what went wrong.

Just to be sure add the following line to the code (method) that gets executed with setInterval and watch after 20-30 minutes if you still get output in the console.

console.log('Yep! I am alive!');

EDIT: Could be anything but try changing the tmstmp method to include a callback function after the POST request gets executed. That way you'll at least know that it works.

function tmstmp() {
    $.post("send_functions.php?act=time", function(data){
        console.log('Yep! I am alive!');
    });
}

Upvotes: -1

user123444555621
user123444555621

Reputation: 152966

That's not supposed to happen. Browsers may indeed reduce the timer resolution to something around 1/s, but not clear the setInterval.

Could there be some bug in your code that causes a clearInterval?

Upvotes: 0

Related Questions