Skip to content

Instantly share code, notes, and snippets.

@jasdeepkhalsa
Last active March 10, 2016 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasdeepkhalsa/82611e7740fa04efd02e to your computer and use it in GitHub Desktop.
Save jasdeepkhalsa/82611e7740fa04efd02e to your computer and use it in GitHub Desktop.
For loop with setTimeout

Inspired by http://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop

For loop with setTimeout

A modified version of Daniel Vassallo's answer, with variables extracted into parameters to make the function more reusable:

First let's define some essential variables:

var startIndex = 0;
var data = [1, 2, 3];
var timeout = 3000;

Next you should define the function you want to run. This will get passed i, the current index of the loop and the length of the loop, in case you need it:

function functionToRun(i, length) {
    alert(data[i]);
}

Self-executing version

(function forWithDelay(i, length, fn, delay) {
   setTimeout(function () {
      fn(i, length);
      i++;
      if (i < length) {
         forWithDelay(i, length, fn, delay); 
      }
  }, delay);
})(startIndex, data.length, functionToRun, timeout);

Function version

function forWithDelay(i, length, fn, delay) {
   setTimeout(function () {
      fn(i, length);
      i++;
      if (i < length) {
         forWithDelay(i, length, fn, delay); 
      }
  }, delay);
}

forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment