vargaking
vargaking

Reputation: 149

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?

Upvotes: 0

Views: 1164

Answers (2)

DJafari
DJafari

Reputation: 13545

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

Upvotes: 1

Quentin
Quentin

Reputation: 944442

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

Upvotes: 1

Related Questions