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?
You cannot PAUSE the setInterval function, you can either STOP it (clearInterval), or let it run.
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
JavaScript continues to run in the background. If it's not running, there should be some other reason. It would be helpful if you could give a code example to work with and work out what might not be happening.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With