Languages
[Edit]
EN

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

3 points
Created by:
Root-ssh
6340

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

 

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.