Skip to content

Instantly share code, notes, and snippets.

@gjohnson
Created November 4, 2011 05:10
Show Gist options
  • Save gjohnson/1338706 to your computer and use it in GitHub Desktop.
Save gjohnson/1338706 to your computer and use it in GitHub Desktop.
Stop Watch
window.StopWatch = (function() {
var seconds = 0;
var minutes = 0;
var timer = null;
var events = {
second: [],
minute: []
};
var emit = function(event, value) {
for (var i = 0, len = events[event].length; i < len; i++) {
events[event][i].call(this, value);
}
};
function StopWatch(cfg) {
cfg = cfg || {};
if (cfg.autostart) {
this.start();
}
}
StopWatch.prototype.on = function(event, callback) {
if (events[event]) {
events[event].push(callback);
}
return this;
};
StopWatch.prototype.stop = function() {
clearInterval(timer);
timer = null;
};
StopWatch.prototype.start = function() {
if (timer === null) {
(function(that) {
timer = setInterval(function() {
seconds++;
if (seconds === 60) {
seconds = 0;
minutes++;
emit.call(that, 'minute', minutes);
}
emit.call(that, 'second', seconds);
}, 1000);
})(this);
}
};
StopWatch.prototype.reset = function() {
this.stop();
seconds = 0;
minutes = 0;
emit('second', seconds);
emit('minute', minutes);
};
return StopWatch;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment