@cran/lib.vue.ref
Version:
Vue Reactivity Extensions
60 lines (47 loc) • 1.15 kB
text/typescript
import { type MaybeWrapped, isWrapped, tryOnScopeDispose, unwrap } from "../utility";
import { readonly, ref, watch } from "vue";
/**
* @since 0.2.0
* @category Controller
*/
export function useInterval (
callback: ( ) => void, ms?: MaybeWrapped<number>, {
paused = false,
leading = false,
trailing = false,
} = { }
) {
let intervalId: ReturnType<typeof setInterval> | null = null;
const isActive = ref(false);
function clear ( ) {
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
}
function stop ( ) {
isActive.value = false;
clear();
if (trailing) { callback(); }
}
function start ( ) {
if (!isActive.value) {
isActive.value = true;
if (leading) { callback(); }
clear();
intervalId = setInterval(callback, unwrap(ms));
}
}
function restart ( ) {
if (isActive.value) {
isActive.value = false;
start();
}
}
if (!paused) { start(); }
if (isWrapped(ms)) {
tryOnScopeDispose(watch(ms, restart));
}
tryOnScopeDispose(stop);
return { isActive: readonly(isActive), stop, start, restart, };
}