@cran/lib.vue.ref
Version:
Vue Reactivity Extensions
48 lines (47 loc) • 1.2 kB
JavaScript
import { isWrapped, tryOnScopeDispose, unwrap } from "../utility";
import { readonly, ref, watch } from "vue";
/**
* @since 0.2.0
* @category Controller
*/
export function useInterval(callback, ms, { paused = false, leading = false, trailing = false, } = {}) {
let intervalId = 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, };
}