Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@stefanmaric
Created December 18, 2018 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanmaric/a883858b6118805028c746a189e5b31d to your computer and use it in GitHub Desktop.
Save stefanmaric/a883858b6118805028c746a189e5b31d to your computer and use it in GitHub Desktop.
Javascript tick function, wrapper around requestAnimationFrame for easier usage
/**
* 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