Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Created April 6, 2017 21:07
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 kyleshevlin/295aa264df33ad877d187024bab0629f to your computer and use it in GitHub Desktop.
Save kyleshevlin/295aa264df33ad877d187024bab0629f to your computer and use it in GitHub Desktop.
Memoization in a rAF loop
const _this = this // the React Component
const ref = this.nodeRef // Using react to get a ref of my DOM element
const { width } = ref.getBoundingClientRect()
const scrollCoeffecient = 0.5 // this is retrieved from a config object in my app
const scrollSpeed = 1 * scrollCoefficient
function loop () {
if (!loop.aggregatedDistance) {
loop.aggregatedDistance = 0
}
loop.aggregatedDistance += scrollSpeed
if (loop.aggregatedDistance > 1) {
const distance = Math.floor(loop.aggregatedDistance)
if ((width + ref.scrollLeft) === ref.scrollWidth) {
ref.scrollLeft = 0
} else {
ref.scrollLeft += distance
}
loop.aggregatedDistance -= distance
}
_this.loopRafId = window.requestAnimationFrame(loop) // Stored to cancel rAF later
}
window.requestAnimationFrame(loop)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment