Skip to content

Instantly share code, notes, and snippets.

@Anthodpnt
Last active July 16, 2019 18:09
Show Gist options
  • Save Anthodpnt/b2e9a8c48f90eb23e5c91a7205904ffe to your computer and use it in GitHub Desktop.
Save Anthodpnt/b2e9a8c48f90eb23e5c91a7205904ffe to your computer and use it in GitHub Desktop.
Performance - Request Animation Frame
/**
* This gist is for Javascript beginners.
* @author: Anthony Du Pont <antho.dpnt@gmail.com>
* @site: https://www.twitter.com/JsGists
*
* You sometimes need to run some code multiples times, on window scroll, on window resize
* or simply every n milliseconds. But what if you want you code to run 60 times per seconds ?
* You could defenitely use a `setTimeout` and even if it's not the best solution
* it would work but! there is a much easier solution, `requestAnimationFrame` (rAF).
*
* `requestAnimationFrame` (rAF) is a method from the `window` object that let you run your code
* 60 times per second (60FPS). It's really useful if you want accurate values from user interactions
* and it becomes even more useful when you want to animate stuffs. So let me show you a simple
* example.
*
* Example:
* I want to watch the window scroll and get the Y scroll position.
* This example is so easy that the two ways will give me accurate values but try to work with
* these values by animating some DOM elements and you will see the 2nd way is more accurate
* than the 1st one.
**/
// Basic way
window.addEventListener('scroll', lookAtScroll);
function lookAtScroll() {
console.log(window.pageYOffset); // Return the Y scroll position
// The problem with this solution is when the user scrolls too fast. The method
// doesn't run fast enough to give you the accurate final Y position.
}
// 60FPS way
window.requestAnimationFrame(lookAtScroll); // Will run the method at least once
function lookAtScroll() {
console.log(window.pageYOffset); // Return the Y scroll position 60 times per second
// The idea here is to call `requestAnimationFrame` again to run the function again.
// It's like a `setTimeout` running the same function 60 times per second.
// Since rAF runs at 60FPS even if you user scrolls really fast the final value for
// the Y position will be accurate.
window.requestAnimationFrame(lookAtScroll);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment