Created
December 18, 2018 17:41
-
-
Save stefanmaric/a883858b6118805028c746a189e5b31d to your computer and use it in GitHub Desktop.
Javascript tick function, wrapper around requestAnimationFrame for easier usage
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
/** | |
* Wrapper around requestAnimationFrame for easier usage. | |
* @param {Function} callback Function to call on each tick, receives last value as only param. | |
* @param {*} [initValue] Optional initial value. | |
* @returns {Function} Clear interval function. | |
*/ | |
const tick = (callback, initValue) => { | |
let unsubscribed = false | |
let lastValue = initValue | |
const handler = () => { | |
if (unsubscribed) return | |
lastValue = callback(lastValue) | |
window.requestAnimationFrame(handler) | |
} | |
window.requestAnimationFrame(handler) | |
return () => { | |
unsubscribed = true | |
} | |
} | |
export default tick |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment