SetTimeout does not work with jquery.each, this

I am trying to add a delay between jquery.removeClass calls iterating through table cells. Cells display correctly without setTimeout, but with setTimeout the code breaks. What am I doing wrong?

function reveal_board() { $("td").each(function() { var t=setTimeout('$(this).removeClass("invisible")', 500); }); } 
+6
source share
4 answers

Try the following:

 function reveal_board() { $("div").each(function(index) { (function(that, i) { var t = setTimeout(function() { $(that).removeClass("invisible"); }, 500 * i); })(this, index); }); } 

It’s usually not good practice to pass a string to setTimeout() , and I don’t think that you can pass any variables when using it this way.

I also wrapped it in a closure to ensure that that always applies to the right element and is not replaced.

Although, like NiftyDude, you can go to the index and use it to display each item in turn.

Working example - http://jsfiddle.net/Cc5sG/

EDIT

It seems you do not need to close:

 function reveal_board() { $("div").each(function(index) { var that = this; var t = setTimeout(function() { $(that).removeClass("invisible"); }, 500 * index); }); } 

http://jsfiddle.net/Cc5sG/1/

+15
source

Your this points to a global window .

 function reveal_board() { $("td").each(function() { $this = $(this); var t=setTimeout(function(){$this.removeClass("invisible");}, 500); }); } 
+2
source

First of all, avoid using a string for the first argument to setTimeout , use the anon function instead, since it is easier to debug and maintain:

 $("td").each(function() { var $this = $(this); var t=setTimeout(function() { $this.removeClass("invisible") }, 500); }); 

Also, I'm not quite sure what you are trying to achieve here (update your question later, and I will adapt my answer), but if you want to remove the invisible class from each td 500 ms after each other, you can use index :

 $("td").each(function() { var $this = $(this); var t=setTimeout(function(index) { $this.removeClass("invisible") }, 500 * (index+1)); }); 
+1
source

Well, I had the same problem and I solved it like that ... But I have no idea about performance or anything else, I used it in a very short loop (maximum 10 elements) and it worked perfectly ... By the way, I used it to add a class, so I will let you know what it gives to remove a class;).

 var elements = $(".elements"); var timeout; elements.each(function(e){ timeout = setTimeout(function(index) { elements[elements.length-e-1].setAttribute('class', elements[elements.length-e-1].getAttribute('class')+' MY-NEW-CLASS'); }, 500 * e); }); 
+1
source

Source: https://habr.com/ru/post/915887/


All Articles