2

I have a javascript for loop iterating through an array of elements and adding a class to them, then remove the class ro change the color of the element for one or two seconds and then revert it to the previous color. I need a synchronous wait in the code between add and remove, which pauses the for loop and do nothing to show the color, or else changing class will not be affected.

for (var i=1; i<array.length; i++){
    array[i-1].addClass('something');
    array[i].addClass('something');
//WAIT, PAUSE THE LOOP for two seconds
    array[i-1].removeClass('something');
    array[i].removeClass('something');
}
s_puria
  • 397
  • 1
  • 8
  • 19
  • the only way that can be done that simply is definitely not recommended – Jaromanda X Aug 18 '17 at 11:58
  • Just wrap it in a timeout, and the browser will have time to repaint – adeneo Aug 18 '17 at 11:58
  • javascript is single threaded. hence this is a bad idea. – Daniel A. White Aug 18 '17 at 11:58
  • 5
    *"I need a synchronous wait in the code between add and remove"* No, you don't, because it would lock up the browser UI. What's the underlying problem you're trying to solve? – T.J. Crowder Aug 18 '17 at 11:58
  • use babel and async / await / yield – GottZ Aug 18 '17 at 11:58
  • 3
    @DanielA.White: *JavaScript* is not single-threaded. *Browsers* run a single main JavaScript thread (and as many worker threads as you like). JavaScript can be, and is, multi-threaded in other environments. – T.J. Crowder Aug 18 '17 at 11:59
  • what T.J. says. in addition to have a bit more clearification: everything your browser renders is running in the same thread as javascript. this means you really want to avoid any syncronous execution at all. as i said: take a look at babel, async, await and yield. they solve your problem of creating asyncronous code even though the code looks syncronous – GottZ Aug 18 '17 at 12:00
  • you can also use yield async and await in your browser but you have to take care about browser support for it. babel is simply a transpiler that compiles future spec javascript down to earlier versions of javascript. in some months you can basically get rid of this and use it directly in every major browser – GottZ Aug 18 '17 at 12:02

0 Answers0