@mcabreradev/filter
Version:
A powerful, SQL-like array filtering library for TypeScript and JavaScript with advanced pattern matching, MongoDB-style operators, deep object comparison, and zero dependencies
31 lines (30 loc) • 867 B
JavaScript
export function debounce(func, delay, options = {}) {
const { leading = false, trailing = true } = options;
let timeoutId = null;
let lastCallTime = 0;
const debounced = function (...args) {
const now = Date.now();
const isLeading = leading && now - lastCallTime > delay;
if (timeoutId) {
clearTimeout(timeoutId);
}
if (isLeading) {
lastCallTime = now;
func.apply(this, args);
}
if (trailing) {
timeoutId = setTimeout(() => {
lastCallTime = Date.now();
func.apply(this, args);
timeoutId = null;
}, delay);
}
};
debounced.cancel = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
};
return debounced;
}