vue3-debounce-input
Version:
Debounce utility for Vue 3, A simple and lightweight Vue3 hook for debouncing values. Ideal for optimizing performance in search fields, input handling, and other scenarios where you want to limit the rate of updates.
52 lines (42 loc) • 1.11 kB
JavaScript
export function debounce(func, wait, options = {}) {
let timeout;
let lastArgs;
let lastThis;
let result;
let lastCallTime;
const { leading = false, trailing = true, immediate = false } = options;
function invokeFunction() {
result = func.apply(lastThis, lastArgs);
lastCallTime = Date.now();
lastArgs = lastThis = null;
}
function cancel() {
clearTimeout(timeout);
lastArgs = lastThis = null;
}
function debounced(...args) {
lastArgs = args;
lastThis = this;
const now = Date.now();
if (immediate && !lastCallTime) {
invokeFunction();
}
const timeRemaining = wait - (now - lastCallTime);
if (timeRemaining <= 0 || timeRemaining > wait) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
if (trailing) {
invokeFunction();
}
}, wait);
} else if (leading && !timeout) {
invokeFunction();
}
lastCallTime = now;
return result;
}
debounced.cancel = cancel;
return debounced;
}