vuestic-ui
Version:
Vue 3 UI Framework
58 lines (57 loc) • 1.62 kB
JavaScript
import { toRef, ref, unref, watch } from "vue";
const useThrottleProps = {
delay: {
type: Number,
default: 0,
validator: (value) => value >= 0
}
};
function useThrottleFunction(fn, props) {
const delay = toRef(props, "delay") ?? 0;
const isThrottled = ref(true);
let lastCallResult = void 0;
return function(...args) {
const invoke = () => fn.apply(this, args);
if (!unref(delay)) {
return invoke();
}
if (isThrottled.value) {
isThrottled.value = false;
setTimeout(() => isThrottled.value = true, unref(delay));
lastCallResult = invoke();
}
return lastCallResult;
};
}
function useThrottleValue(value, props) {
const delay = toRef(props, "delay") ?? 0;
if (!unref(delay)) {
return value;
}
const isThrottled = ref(true);
const previousCallValue = ref();
const previousReturnedValue = ref();
const currentCallValue = ref();
watch(value, () => {
previousCallValue.value = value.value;
const lastCallValue = setTimeout(() => {
currentCallValue.value = previousCallValue.value;
}, unref(delay));
if (isThrottled.value) {
isThrottled.value = false;
currentCallValue.value = value.value;
previousReturnedValue.value = value.value;
clearTimeout(lastCallValue);
setTimeout(() => isThrottled.value = true, unref(delay));
} else {
currentCallValue.value = previousReturnedValue.value;
}
}, { immediate: true });
return currentCallValue;
}
export {
useThrottleValue as a,
useThrottleFunction as b,
useThrottleProps as u
};
//# sourceMappingURL=useThrottle.js.map