0

I am trying to create a simple animation by changing a div class waiting a few millisecond before changing the next div class and so on.

The problem is that the graphics in my test browser ( Chrome ) are only refreshed at the end of all calls and not after each class change.

for(var i = 0; i < 9 ; i++ ){
       document.getElementById(i).setAttribute("class","blueSquare" );
       sleep(500);
    }

here is the jsfiddle to test I have tried various hacks presented in stackoverflow but none seemed to work. I would really appreciate your help.

Community
  • 1
  • 1
FXA
  • 15
  • 5

1 Answers1

0

If I understand correctly you are trying to color the div at an interval one at a time. You can take a look at setTimeout which will apparently serve the purpose of sleep. setTimeout executes a function after certain period.

You also need to take a look at closure since setTimeout is asynchronous operation but loop will not stop executing for setTimeout

var onClick = function() {
    for(var i = 0; i <= 9 ; i++ ){
     (function(i){  // creating closure here
       setTimeout(function(){
         document.getElementById(i).setAttribute("class","blueSquare" );
       },i*500) // 1st div will be colored after 500 msec,second div 1000msec, & so on
     }(i))   
  }
};

$('#button').click(onClick);

JSFIDDLE

brk
  • 43,022
  • 4
  • 37
  • 61