Created
December 9, 2013 21:25
-
-
Save otorras/7881215 to your computer and use it in GitHub Desktop.
A timer class. Based on: require.js, extend.js https://github.com/amatiasq/ , EventEmitter https://github.com/otorras/basics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment