Languages
[Edit]
EN

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

3 points
Created by:
Root-ssh
68980

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

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join