0

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?

giovaZ
  • 1,432
  • 3
  • 20
  • 62
  • 1
    https://stackoverflow.com/questions/16437173/stop-setinterval – Andrew Ice Jan 13 '17 at 14:28
  • Sorry, i didn't add the last part of the question. I also need to resume the interval when i add focus to the tab – giovaZ Jan 13 '17 at 14:42
  • Is it a specific number of iterations. Are these iterations defined in some way? – Andrew Ice Jan 13 '17 at 14:50
  • there're not a specific number of iterations, it's a constant loop that i need to stop/resume(with letting him finish his current action first) when i lose focus to a tab, – giovaZ Jan 13 '17 at 14:56

2 Answers2

1

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);
Community
  • 1
  • 1
Anton Kastritskiy
  • 1,248
  • 1
  • 11
  • 23
1

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);
        });
Andrew Ice
  • 831
  • 4
  • 16