@stimulus-library/utilities
Version:
A library of useful controllers for Stimulus
22 lines (21 loc) • 592 B
JavaScript
export function debounce(func, wait, immediate = false, timoutName) {
timoutName = timoutName || "activeTimeout";
let timeout;
return function (...args) {
const later = () => {
timeout = null;
if (!immediate) {
func.apply(this, args);
}
};
const callNow = immediate && !timeout;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(later, wait);
this[timoutName] = timeout;
if (callNow) {
func.apply(this, args);
}
};
}