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 async loop class with next iteration confirmation?

0 contributions
1 points

In this article, we're going to have a look at how to write own loop asynchronous class that uses callback functions to execute next iteration in proper time or break loop.

Note: read this article to see how to write async loop that executes next iterations in groups - when resources are available.

// ONLINE-RUNNER:browser;

// AsyncLoop class

function AsyncLoop(index, count, onIteration, onFinished) {
	var state = 0;

	function resume() {
		if (state == 1) {
			if (index < count) {
				state = 2;
				var proxy = function() {
					state = 1;
					onIteration(index++, resume, finish);
				};
				setTimeout(proxy, 0);
			} else {
				state = 0;
				if (onFinished) {
					onFinished(true);
				}
			}
		}
	}

	function finish() {
		if (state == 1) {
			state = 0;
			if (onFinished) {
				onFinished(false);
			}
		}
	}

	this.run = function() {
		if (state == 0) {
			index = 0;
			if (onIteration.length > 1) {
				state = 1;
				resume();
			} else {
				while(index < count) {
					onIteration(index);
					index += 1;
				}
				if (onFinished) {
					onFinished(false);
				}
			}
		}
	};
}

// Example helpers:

var timer = new Timer();

function Timer() {
	var t1 = new Date();
	
	this.getTime = function() {
		var t2 = new Date();
		return t2 - t1;
	};
}

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

// Usage example:

function onIteration(i, resume, finish) {
	printMessage('loop iteration');
	setTimeout(resume, 500); // next iteration after 500ms
	// resume() call continues loop
	// finish() call breaks loop
}

function onFinished() {
	printMessage('loop finished');
}

var loop = new AsyncLoop(0, 5, onIteration, onFinished);
loop.run();

printMessage('loop started');
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