Is there any method in javascript that would behave like setInterval() and would stop when user leave the tab and resume when user enter the tab again?
Asked
Active
Viewed 2,054 times
6
-
Thanks for asking, David, but I think the duplicate question will serve your needs quite well! – Kzqai Mar 04 '15 at 18:40
-
@Bergi The other question asks what browsers do with native `setInterval` when the tab is not active. This question is about an emulation of `setInterval` that forces a pause when the tab becomes inactive. They are not duplicates. – Oriol Mar 04 '15 at 19:20
1 Answers
7
You can create your own API, using Visibility API to detect when the tab becomes visible or hidden, and calling native setInterval
and clearInterval
under the hood.
var mySetInterval, myClearInterval;
(function() {
var data = Object.create(null),
id = 0;
mySetInterval = function mySetInterval(func, time) {
data[id] = {
nativeID: setInterval(func, time),
func: func,
time: time
};
return id++;
};
myClearInterval = function myClearInterval(id) {
if(data[id]) {
clearInterval(data[id].nativeID);
delete data[id];
}
};
document.addEventListener('visibilitychange', function() {
if(document.visibilityState == 'visible')
for(var id in data)
data[id].nativeID = setInterval(data[id].func, data[id].time);
else
for(var id in data)
clearInterval(data[id].nativeID);
});
})();
var mySetInterval, myClearInterval;
(function() {
var data = Object.create(null),
id = 0;
mySetInterval = function mySetInterval(func, time) {
data[id] = {
nativeID: setInterval(func, time),
func: func,
time: time
};
return id++;
};
myClearInterval = function myClearInterval(id) {
if(data[id]) {
clearInterval(data[id].nativeID);
delete data[id];
}
};
document.addEventListener('visibilitychange', function() {
if(document.visibilityState == 'visible')
for(var id in data)
data[id].nativeID = setInterval(data[id].func, data[id].time);
else
for(var id in data)
clearInterval(data[id].nativeID);
});
})();
var log = document.getElementById('log'),
timer;
document.getElementById('start').onclick = function() {
var num = 0;
myClearInterval(timer);
timer = mySetInterval(function(){
log.innerHTML = num++;
}, 1e3);
};
<input id="start" type="button" value="Start" />
<span id="log"></span>
Note the API above should not be mixed with the native one, e.g. do not attempt to create with mySetInterval
and clear with clearInterval
. Therefore, the IDs returned by mySetInterval
are deliberately different than the native ones.

Oriol
- 274,082
- 63
- 437
- 513