简体   繁体   中英

jQuery let finish and then stop functions when tab loses focus

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?

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);

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);
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM