Is there a way to pause a function's execution when a user leaves a page?
eg if I have something like: setInterval(cleanGarbage, 3000);
Is there a way to pause it when the user switches his/her tab to a different page, so the function doesn't keep running every 3 seconds while the user isn't even viewing the page?
Hello Emmanuel, here's a pretty simple implementation of what you might consider doing
// Define a global variable to keep track of when this window is in focus
var windowFocused = true;
// Change the value of the windowFocused variable when the window is no longer in focus
window.addEventListener('blur', function(){
windowFocused = false;
}, false);
// Change the value of the windowFocused variable when the window is in focus
window.addEventListener('focus', function(){
windowFocused = true;
}, false);
// Your setInterval() function
setInterval(function() {
if (windowFocused) {
// Carry out your tasks here
console.log('Window focused: ', windowFocused);
}
}, 1000);
welcome to <code>requestAnimationFrame</code>. if you cannot give away from <code>setTimeout</code>, consider at least checking <code>document.hidden</code>.
Look at events that fire when the page goes out of view and set flags accordingly. Be aware that there are some gotchas with different browsers, webviews and so on.
I'm not aware of a function to pause an interval. I would simply stop it and restart the timer when scrolled into view/enters the page.
Edit: typos
Dex
requestAnimationFramepauses execution automatically when the browser window loses focus. You can use a recursivesetTimeoutinstead of asetIntervaland encapsulate it in arequestAnimationFrame.(function cleanGarbageLifecycle() { requestAnimationFrame(function() { setTimeout(function() { cleanGarbage(); cleanGarbageLifecycle(); }, 3000); }); })();