EN
JavaScript - make loop with sleep / loop with time intervals
10
points
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!');
}
});