Created
April 6, 2017 21:07
-
-
Save kyleshevlin/295aa264df33ad877d187024bab0629f to your computer and use it in GitHub Desktop.
Memoization in a rAF loop
This file contains 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
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