Skip to content

Instantly share code, notes, and snippets.

@serverwentdown
Forked from NV/README.md
Last active August 29, 2015 14:15
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 serverwentdown/e399a953b59801a0a261 to your computer and use it in GitHub Desktop.
Save serverwentdown/e399a953b59801a0a261 to your computer and use it in GitHub Desktop.

JavaScript Timer

Run 5 times, with one second delay between calls

t1 = new Timer(500, function(){
  console.log(this.count);
  if (this.count >= 5) {
    this.stop();
  }
});

You can put several functions

t2 = new Timer(500, [
  function(){if (this.count >= 5) this.stop()},
  function(){console.log(this.count)}
]);

Manipulate with all timers

function hi(){console.info("Hi!")}
function whatsUp(){console.info("Whats up?")}
function bye(){console.info("Bye.")}

new Timer(1000, hi);
new Timer(1100, whatsUp);
new Timer(1200, bye);

setTimeout(function(){
  Timer.all.pause();
}, 2000);

setTimeout(function(){
  Timer.all.run();
}, 3000);

setTimeout(function(){
  Timer.all.stop();
}, 4000);
function Timer(delay, callbacks){
if (Object.prototype.toString.call(callbacks) === "[object Function]") {
callbacks = [callbacks];
}
this.callbacks = callbacks;
var that = this;
var id = setInterval(function tick(){
if (!that.running) return;
for (var i=0; i<that.callbacks.length; i++) {
that.callbacks[i].call(that);
}
that.count++;
}, delay);
this.__defineGetter__('id', function(){return id});
this.__defineGetter__('delay', function(){return delay});
Timer.all.push(this);
}
Timer.prototype.running = true;
Timer.prototype.count = 0;
Timer.prototype.pause = function pause(){
this.running = false;
return this;
};
Timer.prototype.run = function run(){
this.running = true;
return this;
};
Timer.prototype.stop = function stop(){
// Unlike pause, once you stop timer, you can't run it again
clearInterval(this.id);
this.stopped = true;
return this;
};
Timer.all = [];
Timer.all.pause = function pause(){
var all = Timer.all;
for (var i=0; i<all.length; i++) {
all[i].pause();
}
return all;
};
Timer.all.run = function run(){
var all = Timer.all;
for (var i=0; i<all.length; i++) {
all[i].run();
}
return all;
};
Timer.all.stop = function stop(){
var all = Timer.all;
for (var i=0; i<all.length; i++) {
all[i].stop();
}
return all;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment