I have a codepen demo that I've worked up that uses several instances of setTimeout
and setInterval
. I've found that there's an issue with setInterval
if the user leaves the page.
You may notice that if you leave the page while this interval is running, the numbers will continue to increment forever. The interval is essentially not getting cleared. This works just fine otherwise.
Here's an example of one of the instances of setInterval
within a setTimeout
.
setTimeout(function() {
var x = parseInt($one.text());
handle = setInterval(function() {
if (x > -5) {
x--;
$one.html(x + 'px');
}
else {
clearInterval(handle);
handle = null;
}
}, 200);
$box.animate({
boxShadow: '-5px 0 0 0 #333'
}, 2000);
}, 7000);
I've tried adding both clearInterval(handle)
and handle = null
in my if/else statement, but I simply can't get the interval to clear if a user leaves the page. Any other ways I can approach this setInterval
? Is this just a javascript limitation?
Update
Strangely enough, when I log the x
value, the console shows it displaying the -1 through -4 numbers correctly. Does clearInterval
not run from another window?