How to create pause or delay in FOR loop?

var wonderfulFunction = function(i) {
   var s = document.getElementById("div1"); //you could pass this element as a parameter as well
   i = i || 0;
   if(i < 10) {
      s.innerHTML = s.innerHTML + i.toString();

      i++;
      //create a pause of 2 seconds.
      setTimeout(function() { wonderfulFunction(i) }, 2000);          
   }
}

//first call
wonderfulFunction(); //or wonderfulFunction(0);

You can't pause javascript code, the whole language is made to work with events, the solution I provided let's you execute the function with some delay, but the execution never stops.


You can't use a delay in the function, because then the change that you do to the element would not show up until you exit the function.

Use the setTimeout to run pieces of code at a later time:

var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {

  // create a closure to preserve the value of "i"
  (function(i){

    window.setTimeout(function(){
      s.innerHTML = s.innerHTML + i.toString();
    }, i * 2000);

  }(i));

}