Languages
[Edit]
EN

JavaScript - how to make loop with sleep / loop with time intervals?

10 points
Created by:
Root-ssh
6442

Simple solution:

// ONLINE-RUNNER:browser;

var i = 0;

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

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

 

1. Custom makeLoop function example

// ONLINE-RUNNER:browser;

function makeLoop(count, duration, onIteration) {
  	var index = 0;
  	var sleep = duration / count;

  	function action() {
    	if (index < count) {
      		onIteration(index++);

      		setTimeout(action, sleep);
    	}
  	}

  	if (index < count) {
    	setTimeout(action, sleep);
  	}
}

// 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!');
  	}
}, 5000);

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.