Created
January 24, 2015 14:16
-
-
Save bloodyowl/f6eeb17333ed6fcd274e to your computer and use it in GitHub Desktop.
Timer
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
var _id = -1 | |
var timersMap = new Map() | |
var Timer = { | |
/** | |
* starts executing `func` at every frame from the moment `setTransition` is called | |
* and during the duration in milliseconds. | |
* | |
* the method returns a number `id` which can be used as `clearTransition` parameter | |
* to stop an active transition (with the same mechanism as `setTimeout` & `clearTimeout`) | |
* | |
* `func` will have a `progress` number value passed as argument, which goes from `0` to `1`, | |
* so that we can track the progression in the active transition. | |
* | |
* @param {Function} func | |
* @param {Number} duration | |
* @returns {Number} id | |
*/ | |
setTransition : function(func, duration) { | |
if(typeof func !== "function") { | |
throw new TypeError("expected a function") | |
} | |
if(typeof duration !== "number" || isNaN(duration)) { | |
throw new TypeError("duration param must be a number") | |
} | |
var id = ++_id | |
var start = Date.now() | |
function tick() { | |
var progress = (Date.now() - start) / duration | |
if(progress >= 1) { | |
// used to make sure the end call has the expected value | |
func(1) | |
timersMap.delete(id) | |
return | |
} | |
func(progress) | |
timersMap.set(id, requestAnimationFrame(tick)) | |
} | |
timersMap.set(id, requestAnimationFrame(tick)) | |
return id | |
}, | |
/** | |
* stops an active transition from its `id`. | |
* | |
* `clearTransition` returns a boolean, `true` if it cancelled a transition, | |
* `false` if the transtion doesn't exist or wasn't running at the time. | |
* | |
* @param {Number} id | |
* @returns {Boolean} | |
*/ | |
clearTransition : function(id) { | |
if(!timersMap.has(id)) { | |
return false | |
} | |
cancelAnimationFrame(timersMap.get(id)) | |
timersMap.delete(id) | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment