@daysnap/horn-use
Version:
horn use
46 lines (45 loc) • 1.08 kB
JavaScript
import { ref, getCurrentScope, onScopeDispose } from 'vue';
function tryOnScopeDispose(fn) {
if (getCurrentScope()) {
onScopeDispose(fn);
return true;
}
return false;
}
/**
* Call function on every `requestAnimationFrame`. With controls of pausing and resuming.
* @param fn
* @param options
*/
export function useRaf(fn, options = {}) {
const { immediate = true } = options;
const isActive = ref(false);
let rafId = null;
function loop() {
if (!isActive.value || !window)
return;
fn();
rafId = window.requestAnimationFrame(loop);
}
function resume() {
if (!isActive.value && window) {
isActive.value = true;
loop();
}
}
function pause() {
isActive.value = false;
if (rafId != null && window) {
window.cancelAnimationFrame(rafId);
rafId = null;
}
}
if (immediate)
resume();
tryOnScopeDispose(pause);
return {
isActive,
pause,
resume,
};
}