double requestAnimationFrame
Google IO17 “Creating UX that ‘just feels right’ with Progressive Web Apps” https://youtu.be/mmq-KVeO-uU
Because of the bug introduced in Chrome and some others, we have to use double
requestAnimationFrame
whenever we find ourselves toggling classes or performing other CSS animations that requires RAF to fire after an action is performed. It’s kinda like an escape hatch to have nice/smooth animation.
“One weird trick to performant touch-response animations with React” > https://medium.com/@owencm/one-weird-trick-to-performant-touch-response-animations-with-react-9fe4a0838116>
https://stackoverflow.com/questions/44145740/how-does-double-requestanimationframe-workDouble RAF is useful for ensuring that animations start before expensive rendering is done. It helps provide smoother user experience by making animations feel reactive. Normal rendering would block the animation from starting. With double RAF as shown here the rendering function safely runs in the main thread after the animation has already started.
https://github.com/ryanve/draf
raf.ts from vant:
import Vue from "vue";
/**
* requestAnimationFrame polyfill
*/
const isServer: boolean = Vue.prototype.$isServer;
let prev = Date.now();
/* istanbul ignore next */
function fallback(fn: FrameRequestCallback): number {
const curr = Date.now();
const ms = Math.max(0, 16 - (curr - prev));
const id = setTimeout(fn, ms);
prev = curr + ms;
return id;
}
/* istanbul ignore next */
const root = (isServer ? global : window) as Window;
/* istanbul ignore next */
const iRaf = root.requestAnimationFrame || fallback;
/* istanbul ignore next */
const iCancel = root.cancelAnimationFrame || root.clearTimeout;
export function raf(fn: FrameRequestCallback): number {
return iRaf.call(root, fn);
}
// double raf for animation
export function doubleRaf(fn: FrameRequestCallback): void {
raf(() => {
raf(fn);
});
}
export function cancelRaf(id: number) {
iCancel.call(root, id);
}