Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

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

0 contributions
10 points

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more