Reputation: 1470
in my code i've got a situation like this:
var t = setInterval(function(e) {
if (document.hasFocus()) {
// Tab Has Focus so,
// Execute some actions
}
},4000);
I've a jQuery interval that every 4 seconds execute some actions. Like animate objects and adding css classes to my DOM.
The problem is that when i change tab ('blur' window event) and then re-add the focus event are re executed.
Is there a method that let the current actions finish and then stop the interval and then resume when page is focused?
Upvotes: 0
Views: 248
Reputation: 841
Well, without your entirety of code. I cannot give you an exact solution. So, this may not be exactly what you're looking for. But it's got a similar concept. Maybe even more than what you actually need:
var i = 0; // Track the iteration we are currently in.
var t; // Used to set and clear intervals.
function timer() {
t = setInterval(function(e) {
// Whereas I keep track of Iterations, you may wanna keep track of specific styles, etc...
console.log(i);
localStorage.setItem('currentIteration', i);
i++;
},1000);}
timer();
$(window).focus(function() {
// If localStorage is set, continue from where we left off.
var currentIteration = localStorage.getItem('currentIteration');
if ( currentIteration != "" ) {
i = ( Number(currentIteration) + 1 );
}
timer();
});
$(window).blur(function() {
// You could command the css application to finish on tab leave.
// Although, it should already finish, since it's a function already in progress.
clearInterval(t);
});
Upvotes: 1
Reputation: 1333
A little google around would help, but here is what I found
var t = setInterval(function(e) {
if (document.hasFocus()) {
// Tab Has Focus so,
// Execute some actions
} else {
// if not in focus
// stop the interval
clearInterval(t);
}
},4000);
Upvotes: 1