Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❀ đŸ’»
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

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

0 contributions
3 points

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

 

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