Languages
[Edit]
EN

JavaScript - how to make async loop that continues iteration when is ready in modern js?

3 points
Created by:
Root-ssh
175460

In this article, we're going to have a look at how to write own asynchronous loop that executes next iteration in proper time or breaks loop.

Note: read this article to see how to write async loop that executes next iterations on calling callback function - this approach is recommended with old JavaScript.

// ONLINE-RUNNER:browser;

// async loop method

let sleepLoop = async (milliseconds) => {
  	var promise = new Promise((resolve, reject) => {
    	setTimeout(resolve, milliseconds);
    });
  	return promise;
};

let runLoop = async (onStarted, onIteration, onFinished) => {
    await onStarted();

	for (var i = 0; i < 5; ++i) {
      	var result = await onIteration(i);
      
      	if (result === false) {
        	break;
        }
    }

  	await onFinished();
};

// Helpers utils:

class Timer {
	constructor() {
      	this.t1 = new Date();
    }
	
	getTime() {
		let t2 = new Date();
		return t2 - this.t1;
	}
}

let timer = new Timer();

let printMessage = (message) => {
    console.log('[' + message + ', time=' + timer.getTime() + ']');
};

// Usage example:

let onStarted = async () => {
	printMessage('loop started');
};

let onIteration = async (i) => {
	printMessage('loop iteration');
	await sleepLoop(500); // next iteration after 500ms
  
  	//return false; // true - keeps loop execution, false - breaks loop execution
};

let onFinished = async (i) => {
	printMessage('loop finished');
};

runLoop(onStarted, onIteration, onFinished);

 

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