Skip to content

Instantly share code, notes, and snippets.

@otorras
Created December 9, 2013 21:25
Show Gist options
  • Select an option

  • Save otorras/7881215 to your computer and use it in GitHub Desktop.

Select an option

Save otorras/7881215 to your computer and use it in GitHub Desktop.

Revisions

  1. otorras created this gist Dec 9, 2013.
    53 changes: 53 additions & 0 deletions timer.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    define(['core/extend', 'core/emitter'], function(extend, EventEmitter) {
    'use strict';

    var Timer = extend(EventEmitter, {
    constructor: function(precision) {
    this.precision = precision;
    this.watchers = [];
    this.ticks = 0;
    this.tick = this.tick.bind(this);
    },

    start: function() {
    this.handler = setInterval(this.tick, this.precision);
    return this;
    },

    stop: function() {
    this.pause();
    this.emit('stop', this.ticks, this.precision);
    return this;
    },

    pause: function() {
    if (this.handler) {
    clearInterval(this.handler);
    delete this.handler;
    }
    },

    reset: function() {
    this.pause();
    this.watchers.length = 0;
    this.ticks = 0;
    },

    addWatcher: function(time, listener) {
    this.watchers[time] = listener;
    },

    tick: function() {
    ++this.ticks;
    this.emit('tick', this.ticks, this.precision);
    var stopWatch = this.watchers[this.ticks * this.precision];
    if (stopWatch) { stopWatch(); }
    }
    }, {
    second: 1000,
    minute: 60 * 1000,
    hour: 60 * 60 * 1000
    });

    return Timer;
    });