Skip to content

Instantly share code, notes, and snippets.

@jonbarrow
Created October 2, 2017 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonbarrow/09dfcc8192f5eed42873bc1756d21128 to your computer and use it in GitHub Desktop.
Save jonbarrow/09dfcc8192f5eed42873bc1756d21128 to your computer and use it in GitHub Desktop.
class AsyncLoop {
constructor(length, looper, cb) {
this.i = -1;
this.length = length;
this.looper = looper;
this.callback = cb;
this.loop();
}
loop() {
this.i++;
if (this.i == this.length) {
if (this.callback) {
this.callback();
}
return;
}
setTimeout(function() {
this.looper(this.i);
}.bind(this), 0);
}
stop() {
this.i = this.length;
if (this.callback) {
this.callback();
}
}
}
///////////
// USAGE //
///////////
current_loop = new AsyncLoop(9999, function(i) {
console.log(i)
if (i > 20) {
current_loop.stop();
return;
}
current_loop.loop();
}, function() {
console.log('All done!');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment