avocado-old/packages/timing/animation-frame.js
2019-03-28 12:36:57 -05:00

75 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Adapted from https://gist.github.com/paulirish/1579671#gistcomment-91515
let raf = window.requestAnimationFrame;
let caf = window.cancelAnimationFrame;
// Vendors?
const w = window;
for (const vendor of ['ms', 'moz', 'webkit', 'o']) {
if (raf) {
break;
}
raf = window[`${vendor}RequestAnimationFrame`];
caf = window[`${vendor}CancelAnimationFrame`];
caf = caf || window[`${vendor}CancelRequestAnimationFrame`];
}
// rAF is built in but cAF is not.
if (raf && !caf) {
const browserRaf = raf;
const canceled = {}
raf = (fn) => {
const id = browserRaf((time) => {
if (!(id in canceled)) {
return fn(time);
}
delete canceled[id];
});
return id;
};
caf = (id) => {
canceled[id] = true;
};
}
// Handle legacy browsers which dont implement rAF
if (!raf) {
let targetTime = 0;
raf = (fn) => {
const currentTime = +new Date;
targetTime = Math.max(targetTime + 16, currentTime);
const wfn = () => {
fn(+new Date);
}
return window.setTimeout(wfn, targetTime - currentTime);
};
caf = (id) => {
window.clearTimeout(id);
};
}
export {caf as cancelAnimationFrame};
export {raf as requestAnimationFrame};
// setInterval, but for animations. :)
let said = 0
const handles = {}
export function setAnimation(fn) {
const id = ++said;
const wfn = (time) => {
if (!handles[id]) {
return;
}
fn(time);
handles[id] = raf(wfn);
}
handles[id] = raf(wfn);
return id;
}
export function clearAnimation (id) {
caf(handles[id]);
delete handles[id];
}