Skip to content

Instantly share code, notes, and snippets.

@vstarck
Created December 22, 2011 20:39
Show Gist options
  • Save vstarck/1511768 to your computer and use it in GitHub Desktop.
Save vstarck/1511768 to your computer and use it in GitHub Desktop.
Timer.js
function Timer(interval) {
this.handlers = {};
this.started = false;
this.interval = interval;
};
Timer.prototype.tick = function () {
if (!this.started) {
return;
}
var self = this;
this.id = setTimeout(function () {
self.tick();
}, this.interval);
this.trigger('tick');
};
Timer.prototype.start = function () {
if (this.started) {
return;
}
this.started = true;
this.trigger('start');
this.tick();
};
Timer.prototype.stop = function () {
this.started = false;
clearInterval(this.id);
this.trigger('stop');
};
Timer.prototype.on = function (ev, handler) {
if (!this.handlers[ev]) {
this.handlers[ev] = [];
}
this.handlers[ev].push(handler);
return this;
}
Timer.prototype.trigger = function (ev) {
if (!this.handlers[ev]) {
return;
}
var handlers = this.handlers[ev];
for (var i = 0, l = handlers.length; i < l; i++) {
handlers[i].call(this);
}
return this;
}
Timer.prototype.onTick = function (handler) {
return this.on('tick', handler);
};
Timer.prototype.onStart = function (handler) {
return this.on('start', handler);
};
Timer.prototype.onStop = function (handler) {
return this.on('stop', handler);
};
var t = new Timer(2000);
var i = 0;
t.onTick(function() {
console.log(i++);
});
t.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment