Last active
August 29, 2015 14:05
-
-
Save jasonbyrne/c40302a8ce25d377c18c to your computer and use it in GitHub Desktop.
Better Timing Management
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
/** | |
* Created by jasonbyrne on 8/30/14. | |
*/ | |
window.JCB = window.JCB || {}; | |
JCB.Timing = (function(){ | |
// Self | |
var me = {}; | |
// Private Properties | |
var _timers = {}, | |
_lastTick = new Date().getTime(), | |
_now = null, | |
_animFrame = (function(){ | |
return window.requestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
function( callback ){ | |
window.setTimeout(callback, 1000 / 60); | |
}; | |
})(); | |
// Private Methods | |
var _tick = function() { | |
_animFrame(_tick); | |
_now = new Date().getTime(); | |
for (id in _timers) { | |
_timers[id].diff = (_now - _timers[id].lastTick); | |
if (_timers[id].interval <= _timers[id].diff) { | |
_timers[id].count++; | |
_timers[id].lastTick = _now; | |
_timers[id].callback(_timers[id]); | |
// If the reps have been expired | |
if ( | |
_timers[id].reps > 0 && | |
_timers[id].count >= _timers[id].reps | |
) { | |
me.removeTimer(id); | |
} | |
} | |
} | |
_lastTick = _now; | |
return me; | |
}; | |
// Public methods | |
me.addTimer = function(callback, interval, reps) { | |
var id = new Date().getTime() + Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5); | |
_timers[id] = { | |
'id': id, | |
'interval': interval, | |
'callback': callback, | |
'count': 0, | |
'reps': reps || 0, | |
'diff': 0, | |
'lastTick': _lastTick | |
}; | |
return id; | |
}; | |
me.removeTimer = function(id) { | |
delete _timers[id]; | |
}; | |
me.getTimer = function(id) { | |
return _timers[id]; | |
}; | |
me.getLastTick = function() { | |
return _lastTick; | |
}; | |
// Done | |
return _tick(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment