Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create pause or delay in FOR loop?

Tags:

I am working on a website, where I need to create a pause or delay.
So please tell me How to create pause or delay in for loop in javascript or jQuery

This is a test example

 var s = document.getElementById("div1");
 for (i = 0; i < 10; i++) {
     s.innerHTML = s.innerHTML + i.toString();
     //create a pause of 2 seconds.
  }
like image 348
jams Avatar asked Apr 07 '12 22:04

jams


People also ask

How do you slow down a loop?

Just put the timeout in the for-loop, and the loop is less fast: When we run the code with setTimeout, the following happens: nothing happens for 1 second; then all the logs come up in a flash.

How do you delay a loop in Java?

Delay loops can be created by specifying an empty target statement. For example: for(x=0;x<1000;x++); This loop increments x one thousand times but does nothing else.

How do you use await inside a loop?

You need to place the loop in an async function, then you can use await and the loop stops the iteration until the promise we're awaiting resolves. You could also use while or do.. while or for loops too with this same structure.


2 Answers

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));

}
like image 165
Guffa Avatar answered Sep 30 '22 07:09

Guffa


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.

like image 34
nicosantangelo Avatar answered Sep 30 '22 06:09

nicosantangelo