简体   繁体   中英

setTimeout inside setInterval does not work well

My code should change the class of the item in every second and repeat it forever.

function myFunction() {
 setInterval(function() {
    $("#item").addClass("class-one").removeClass("class-two");
    setTimeout(function(){
      $("#item").addClass("class-two").removeClass("class-one");
    }, 1000);
  },1000);
}

myFunction();

First time the code works well, but after the loop starts again, it starts switching very fast. Can anybody tell me why?

  1. The interval starts
  2. 1 second later the interval resolves:
  • classes are switched over
  • the timeout is triggered
  1. 1 second later:
    • The timeout resolves
      • classes are switched over
    • The interval resolves
      • classes are switched over
      • the timeout is triggered

You probably want the timeout time to be half the interval time, not the same as it.


A better approach entirely would be to use one class and use jQuery().toggle to toggle it on and off every second (using one interval and no timeouts).

correct way:

var i = 0;
function myFunction() {
  setInterval(function() {
    if(i % 2 == 0) {
      $("#item").addClass("class-one").removeClass("class-two");
    } else {
      $("#item").addClass("class-two").removeClass("class-one");
    }
    i++;
  },1000);
}

myFunction();

or with your solution: ( increase 1 second of setInterval time )

function myFunction() {
 setInterval(function() {
    $("#item").addClass("class-one").removeClass("class-two");
    setTimeout(function(){
      $("#item").addClass("class-two").removeClass("class-one");
    }, 1000);
  },2000);
}

myFunction();

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