Languages
[Edit]
EN

JavaScript - how to make async loop class with next iteration confirmation?

1 points
Created by:
Root-ssh
175320

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, onStarted, onIteration, onFinished) {

    var READY = 0;
    var EXECUTING = 1;
    var WAITING = 2;

  	var state = READY;

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

	function finish() {
		if (state == EXECUTING) {
			state = READY;
			if (onFinished) {
				onFinished(false);
			}
		}
	}

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

// Usage example:

function onStarted() {
	console.log('loop started');
}

function onIteration(i, resume, finish) {
	console.log('loop iteration');
  	setTimeout(resume, 500); // next iteration after 500ms
  
	// resume() - continues loop
	// finish() - breaks loop
}

function onFinished() {
	console.log('loop finished');
}

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

Alternative titles

  1. JavaScript - how to make async loop class with next iteration callback function?
  2. JavaScript - how to make asynchronous loop class with next iteration callback function?
  3. JavaScript - how to make asynchronous loop class with next iteration confirmation?
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