Skip to content

Instantly share code, notes, and snippets.

@Noah-Huppert
Created May 25, 2014 01:58
Show Gist options
  • Save Noah-Huppert/ff536b9af9dc22631e7a to your computer and use it in GitHub Desktop.
Save Noah-Huppert/ff536b9af9dc22631e7a to your computer and use it in GitHub Desktop.
JS Async setInterval
function asyncInterval(){
var self = this;
self.interation = {};
self.interationNumber = 0;
self.asyncCompleteFlag = false;
self.checkInterval = undefined;
self.start = function(toRun, speed){//toRun must be passed asyncInterval, so it can set asyncCompleteFlag
self.checkInterval = setInterval(function(){
self.checkComplete(toRun, speed);
}, 10);
};
self.end = function(){
if(!!self.checkInterval){
clearInterval(self.checkInterval);
}
self.checkInterval = undefined;
self.asyncCompleteFlag = false;
};
self.done = function(){
self.asyncCompleteFlag = true;
};
self.checkComplete = function(toRun, speed){
if(!!self.interation[self.interationNumber]){//Currently waiting
var interationStart = self.interation[self.interationNumber];
var dif = Date.now() - interationStart;
if(dif >= speed && self.asyncCompleteFlag){//Speed has been met, Async function has completed
self.interationNumber = self.interationNumber + 1;
self.asyncCompleteFlag = false;
}
} else{//Start new waiting
self.interation[self.interationNumber] = Date.now();
toRun(self);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment