0

I want to go through each element with a certain class, and show them one by one, but will a random delay between them.

The tricky part is, that I want to do it in a linear fashion, so I don't start off a new thread for each element, since then the elements will be shown randomly (because the delay is also random).

After this is done, I would like to run another part of the code.

What i have now looks like this, but you can see that the delay is set to a fixed amount (in order not to mess up the order of the elements)

jQuery('.myclass').each(function(index) { 
    jQuery(this).delay(1000 * index).fadeIn(0); 
}).promise().done(function() {
    //run code that has to run when the iteration is finished
});

Is there another way to achieve this, where I might not even need to use a promise, and a callback for when the iteration should be done?

A more linear approach, where I would "sleep" inbetween iteration, like this?

jQuery('.myclass').each(function(index) {
    jQuery(this).show(); 
    //sleep somehow for 1 or 2 seconds
})
//run code that has to run when the iteration is finished
Laureant
  • 979
  • 3
  • 18
  • 47
  • Take a look at https://stackoverflow.com/a/2358350/4417306 – Mark Oct 22 '18 at 11:26
  • instead of looping the elements, you'd need to chain the promises returned by the fade events - i.e. use the "done" state of the previous one as the moment to start the next one. – ADyson Oct 22 '18 at 11:26
  • Propably duplicate of https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout – Matthi Oct 22 '18 at 11:28

0 Answers0