Amit
Amit

Reputation: 22076

How to create pause or delay in FOR loop?

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.
  }

Upvotes: 23

Views: 68864

Answers (15)

Cezary Mikołajczyk
Cezary Mikołajczyk

Reputation: 1

That would work.

(async function () {
  "use strict";
  var wt = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); var t = ["sample", "sample", "sample"];

  await wt(1000)

  for (let i = 0; i < t.length; i++) {
      await wt(1000)
    }
  }
})();

Upvotes: 0

Shyam Jayakannan
Shyam Jayakannan

Reputation: 31

You can pause within loops using async and await. Here is an example. Carry out your actions in the area above the await line (console log in the example)

async function yay() {
  for (let i = 0; i < 5; i++) {
    // actions here
    console.log(i);

    await new Promise(resolve => setTimeout(resolve, 1000));
  }
};

yay();

Upvotes: 3

Atul
Atul

Reputation: 36

I am using while loop and check the pause variable to check the user pause/resume the code.

var pause = false;
(async () => {
  for (let index = 0; index < 1000; index++) {
    while (pause) {
      await new Promise((res) => setTimeout(res, 1000));
      console.log("waiting");
    }
    await new Promise((res) => setTimeout(res, 1000));
    console.log(index);
  }
})();

const pausefunc = async () => {
  pause = true;
};
const playfunc = () => {
  pause = false;
};
    <button onclick="playfunc()">Play</button>
    <button onclick="pausefunc()">Pause</button>

Upvotes: 0

Ben Bieler
Ben Bieler

Reputation: 1598

It is not possible to pause a loop. However you can delay the execution of code fragments with the setTimeout() function. It would not make a lot of sense to pause the entire execution anyway.

Upvotes: 0

BaSsGaz
BaSsGaz

Reputation: 784

The way I found was to simply use setInterval() to loop instead. Here's my code example :

var i = 0;
var inte = setInterval(() => {
    doSomething();

    if (i == 9) clearInterval(inte);
    i++;
}, 1000);

function doSomething() {
    console.log(i);
};

This loops from 0 to 9 waiting 1 second in between each iteration.

Output :

0 1 2 3 4 5 6 7 8 9

Upvotes: 0

Jon649
Jon649

Reputation: 289

I used a do...while loop to put a delay in my code for a modal dialog that was closing too quickly.

your stuff....

var tNow = Date.now();
var dateDiff = 0;
do {
    dateDiff = Date.now() - tNow;
} while (dateDiff < 1000); //milliseconds - 2000 = 2 seconds

your stuff....

Upvotes: -1

Sean Novak
Sean Novak

Reputation: 520

I am executing a function where I need access to the outside object properties. So, the closure in Guffa solution doesn't work for me. I found a variation of nicosantangelo solution by simply wrapping the setTimeout in an if statement so it doesn't run forever.

    var i = 0;
    function test(){

        rootObj.arrayOfObj[i].someFunction();
        i++;
        if( i < rootObj.arrayOfObj.length ){
            setTimeout(test, 50 ); //50ms delay
        }

    }
    test();

Upvotes: 0

BishopZ
BishopZ

Reputation: 6378

While several of the other answers would work, I find the code to be less elegant. The Frame.js library was designed to solve this problem exactly. Using Frame you could do it like this:

var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {
   Frame(2000, function(callback){ // each iteration would pause by 2 secs
      s.innerHTML = s.innerHTML + i.toString();
      callback();
   }); 
}
Frame.start();

In this case, it is nearly the same as the examples that use setTimeout, but Frame offers a lot of advantages, especially if the you are trying to do multiple or nested timeouts, or have a larger JS application that the timeouts need to work within.

Upvotes: 0

SKing7
SKing7

Reputation: 2356

if you want to create pause or delay in FOR loop,the only real method is

while (true) {
    if( new Date()-startTime >= 2000) {
        break;
    }
}

the startTime is the time before you run the while but this method will cause the browsers become very slow

Upvotes: 2

Amit
Amit

Reputation: 22076

I tried all one, but I think this code is better one, it is very simple code.

var s = document.getElementById("div1");
var i = 0;
setInterval(function () {s.innerHTML = s.innerHTML + i.toString();  i++;}, 2000);

Upvotes: 3

nicosantangelo
nicosantangelo

Reputation: 13716

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.

Upvotes: 8

zatatatata
zatatatata

Reputation: 4821

The following code is an example of pseudo-multithreading that you can do in JS, it's roughly an example of how you can delay each iteration of a loop:

var counter = 0;

// A single iteration of your loop
// log the current value of counter as an example
// then wait before doing the next iteration
function printCounter() {
    console.log(counter);
    counter++;
    if (counter < 10)
        setTimeout(printCounter, 1000);
}

// Start the loop    
printCounter();

Upvotes: 0

Guffa
Guffa

Reputation: 700152

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

}

Upvotes: 29

Starx
Starx

Reputation: 78971

This is how you should do it

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

Upvotes: 0

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

It is impossible to directly pause a Javascript function within a for loop then later resume at that point.

Upvotes: 0

Related Questions