gtht-miniapp-sdk
Version:
gtht-miniapp-sdk 是一套基于 Uniapp + Vue3 框架开发的兼容多端的 UI 组件库
50 lines (49 loc) • 1.23 kB
JavaScript
import { onUnmounted, shallowReadonly, shallowRef, unref, } from 'vue';
export function useTimeout(cb, interval, options = {}) {
const { immediate = false, immediateCallback = false } = options;
let realInterval = 100;
if (typeof interval === 'number') {
realInterval = interval;
}
else if (typeof interval === 'function') {
realInterval = interval();
}
else {
realInterval = unref(interval);
}
const isPending = shallowRef(false);
let timer = null;
function clear() {
if (timer) {
clearTimeout(timer);
timer = null;
}
}
function stop() {
isPending.value = false;
clear();
}
function start(...args) {
if (immediateCallback)
cb();
clear();
isPending.value = true;
timer = setTimeout(() => {
isPending.value = false;
timer = null;
cb(...args);
}, realInterval);
}
if (immediate) {
start();
}
onUnmounted(() => {
stop();
});
return {
isPending: shallowReadonly(isPending),
start,
stop,
};
}
export const useSetTimeout = useTimeout;