Languages
[Edit]
EN

JavaScript - make loop with sleep / loop with time intervals

10 points
Created by:
Root-ssh
175340

In this article, we would like to show you how to make a loop with time intervals in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

var i = 0;

function makeIteration() {
  if (i < 5) {
    // 5 iterations
    console.log((i + 1) + ' / 5');
    setTimeout(makeIteration, 500); // 0.5 second waiting
  }
  i += 1;
}

setTimeout(makeIteration, 500); // 0.5 second waiting

 

Reusable function example

// ONLINE-RUNNER:browser;

function makeLoop(count, duration, onIteration) {
  var index = 0;
  var sleep = duration / count;
  var action = function() {
    if (index < count) {
      onIteration(index++);
      setTimeout(action, sleep);
    }
  };
  if (index < count) {
    setTimeout(action, sleep);
  }
}


// Usage example:

var iterationsCount = 5;
var loopDuration = 2000; // 2 seconds duration for all loop

makeLoop(iterationsCount, loopDuration, function (index) {
  console.log('Iteration: ' + (index + 1) + ' / ' + iterationsCount + '.');
  if (index == iterationsCount - 1) {
    console.log('Loop finished!');
  }
});

Alternative titles

  1. JavaScript - how to make loop with sleep / loop with time intervals?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join