Skip to content

Instantly share code, notes, and snippets.

@vstarck
Created October 13, 2011 13:43
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 vstarck/1284252 to your computer and use it in GitHub Desktop.
Save vstarck/1284252 to your computer and use it in GitHub Desktop.
Infinite async loop
var infiniteTimedLoop = (function() {
var
task,
interval = 100,
status = false,
i = 0;
function start() {
if(!status) {
return;
}
task(i++);
setTimeout(start, interval);
};
return {
setInterval: function(ms) {
interval = ms;
return this;
},
start: function() {
status = true;
start();
return this;
},
stop: function() {
status = false;
return this;
},
sleep: function(ms) {
var self = this;
this.stop();
setTimeout(self.start, ms);
return this;
},
do: function(newTask) {
task = newTask;
return this;
}
};
})();
// API
// Set the task
infiniteTimedLoop.do(console.log);
// Start
infiniteTimedLoop.start();
// Sleep 1 second (1000 ms)
infiniteTimedLoop.sleep(1000);
// Stop
infiniteTimedLoop.stop();
// And start again!
infiniteTimedLoop.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment