just-animate
Version:
_Making Animation Simple_
50 lines (49 loc) • 1.18 kB
JavaScript
import { _ } from '../utils/constants';
import { push, includes, remove } from '../utils/lists';
import { dispatch } from '../store';
import { TICK } from '../actions';
const raf = requestAnimationFrame;
const caf = cancelAnimationFrame;
const now = () => performance.now();
const active = [];
const deltas = {};
let lastHandle = _;
let lastTime = _;
function cancel() {
caf(lastHandle);
lastHandle = lastTime = _;
}
function update() {
const len = active.length;
lastTime = lastTime || now();
if (!len) {
cancel();
return;
}
const thisTime = now();
const delta = thisTime - lastTime;
lastTime = thisTime;
lastHandle = raf(update);
for (let i = len - 1; i > -1; i--) {
const activeId = active[i];
deltas[activeId] += delta;
dispatch(TICK, activeId, delta);
}
}
export function loopOn(id) {
if (!includes(active, id)) {
deltas[id] = 0;
push(active, id);
}
if (!lastHandle) {
lastHandle = raf(update);
}
}
export function loopOff(id) {
if (remove(active, id)) {
delete deltas[id];
}
if (!active.length) {
cancel();
}
}