Last active
August 29, 2015 14:00
-
-
Save victornpb/11202400 to your computer and use it in GitHub Desktop.
Constructor that create a Loop object to run blocking loops, but allow it to be interrupted when requested to give a change to make DOM updates.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Constructor that create a Loop object to run blocking loops, but allow | |
* it to be interrupted when requested to give a change to make DOM updates | |
* @author Victor B - www.vitim.us | |
*/ | |
function AsyncLoop(){ | |
this.loop; //called on every loop | |
this.onUpdate; //called when the loop is interrupted | |
this.onComplete; //called when the loop is finished | |
this.requestInterruptToUpdateDOM = false; | |
} | |
AsyncLoop.prototype.run = function(){ | |
var self = this; | |
function loop(){ | |
while(true){ | |
//do stuff | |
if(!self.loop.call()){ | |
if(self.onComplete) self.onComplete(); | |
return; | |
} | |
if(self.requestInterruptToUpdateDOM) break; //break loop to let DOM update | |
} | |
if(self.onUpdate) self.onUpdate(); | |
setTimeout(loop, 0); //async resume loop; | |
} | |
loop(); | |
} | |
/* example | |
var A = new AsyncLoop(); | |
A.loop = function(){ | |
//do some extensive computation | |
//show progress every n iterarions | |
if() A.requestInterruptToUpdateDOM = true; | |
//when done return false to break the look | |
return !done; | |
} | |
A.onUpdate = function(){ | |
//print progress | |
} | |
A.onComplete = function(){ | |
//done | |
//print results | |
} | |
A.run(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment