javascript - Insert a delay between every .each -


i've found few other questions pertaining this, answers didn't work me, i'm checking see if there's newer or work. essentially, i'm updating divs in .each in jquery, want them update couple seconds apart. here's i've tried:

function randomcolor() { $('div').each(function(i) {      settimeout(function() {          var colors = ['blue', 'green'];         var n = math.floor(math.random() * colors.length);         var color = colors[n];         $(this).addclass(color);     }, 500 + (i * 500)); }); } 

i've tried using separate function:

function randomcolor() { $('div').each(function(i) {     var time = 500;     settimeout(function() {          applycolor($(this));      }, time);     time += 500; }); } function applycolor(div) {     var colors = ['blue', 'green'];     var n = math.floor(math.random() * colors.length);     var color = colors[n];     $(div).addclass(color); } 

both of these return no errors, divs don't updated. if run code without settimeout, works perfectly. i've tried using delay in fashion:

$('div').delay(1000).each(function() { ... }); 

and delayed 1 second, updated @ once after second. if move delay down near addclass line, stops working altogether again. can point out (hopefully simple) mistake?

you're creating anonymous function , inside function this has different meaning (i.e., window object).

one solution cache this:

var $this = $(this); settimeout(function() {      var colors = ['blue', 'green'];     var n = math.floor(math.random() * colors.length);     var color = colors[n];     $this.addclass(color); }, 500 + (i * 500)); 

Popular posts from this blog