UsopleskCz UsopleskCz - 1 month ago 8
jQuery Question

jQuery - setTimeout does not work

There is my script: https://jsfiddle.net/hcsofjaa/1/
I want to change color of these cells every 2000ms one by one, but It seems the setTimeout function does not work properly. Does anybody know, where is the problem?

$("#button").click(function(){
for (var i = $("span").length; i > 0; i--) {

setTimeout(function(){
$("span:nth-child("+i+")").css("background-color","blue");
}, 2000);

}

Answer

1) $(function) is important - bind click event to element after it rendered.

2) 2000 * i : button colors change in the gap of 2000

$(function(){
  $("#button").click(function(){
  $("span").each(function(i){
   var e = this;
   setTimeout(function(){
     $(e).css("background-color","blue");
   }, 2000 * i);
   });     
   });
});