Jump to Categories

requestAnimationFrame

In it's most simplest form. The callback function is automatically passed a timestamp indicating the precise time requestAnimationFrame() was called

function doSomething(timestamp) {
    console.log(timestamp)
    requestAnimationFrame(doSomething);
}
requestAnimationFrame(doSomething);

To be used instead of using a setTimeout() or setInterval() as, when we call requestAnimationFrame() repeatedly to create an animation, we are assured that our animation code is called when the user's computer is actually ready to make changes to the screen each time, resulting in a smoother, more efficient animation. Furthermore, code called via requestAnimationFrame() and running inside background tabs in your browser are either paused or slowed down significantly (to 2 frames per second or less) automatically to further save user system resources (javascriptkit.com)

ES6 Template

const time = {
    start: performance.now(),
    total: 2000
};

const tick = now => {
    time.elapsed = now - time.start;
    if (time.elapsed < time.total) requestAnimationFrame(tick);                                                 
};                

requestAnimationFrame(tick);

See the Pen requestAnimationFrame example by Shane Prendergast (@webknit) on CodePen.

References