Last active
December 18, 2015 01:28
-
-
Save japboy/5703677 to your computer and use it in GitHub Desktop.
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
'use strict' | |
# | |
# Timer manager | |
# | |
# Usage: | |
# | |
# TimerManager.setInterval fn, 1000 | |
# TimerManager.setTimeout fn, 1000 | |
# | |
class Timer | |
get: (prop) => | |
val = @["_#{prop}"] or undefined | |
return val | |
constructor: (options) -> | |
options = {} unless options | |
@_interval = options.interval or undefined | |
@_timestamp = options.timestamp or undefined | |
@_callback = options.callback or undefined | |
class TimerManager | |
_intervalId: undefined | |
_timers: [] | |
_add: (options) => | |
timer = new Timer options | |
@_timers.push timer | |
_iterate: => | |
now = (new Date()).getTime() | |
for timer, i in @_timers | |
timestamp = timer.get 'timestamp' | |
if now >= timestamp | |
interval = timer.get 'interval' | |
callback = timer.get 'callback' | |
if interval | |
callback() | |
@setInterval callback, interval | |
@_timers.splice i, 1 | |
else | |
callback() | |
@_timers.splice i, 1 | |
destroy: => | |
clearInterval @_intervalId | |
setTimeout: (callback, millisec) => | |
now = (new Date()).getTime() | |
timeout = now + millisec | |
options = | |
timestamp: timeout | |
callback: callback | |
@_add options | |
setInterval: (callback, millisec) => | |
now = (new Date()).getTime() | |
timeout = now + millisec | |
options = | |
timestamp: timeout | |
interval: millisec | |
callback: callback | |
@_add options | |
constructor: () -> | |
@_intervalId = setInterval @_iterate, 1 | |
@TimerManager = new TimerManager() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment