Reputation: 149
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
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
Reputation: 944442
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