1.1 KiB
1.1 KiB
title, tags, firstSeen, lastUpdated
| title | tags | firstSeen | lastUpdated |
|---|---|---|---|
| debounce | function,intermediate | 2018-01-28T15:18:26+02:00 | 2020-10-19T18:51:03+03:00 |
Creates a debounced function that delays invoking the provided function until at least ms milliseconds have elapsed since the last time it was invoked.
- Each time the debounced function is invoked, clear the current pending timeout with
clearTimeout()and usesetTimeout()to create a new timeout that delays invoking the function until at leastmsmilliseconds has elapsed. - Use
Function.prototype.apply()to apply thethiscontext to the function and provide the necessary arguments. - Omit the second argument,
ms, to set the timeout at a default of0ms.
const debounce = (fn, ms = 0) => {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), ms);
};
};
window.addEventListener(
'resize',
debounce(() => {
console.log(window.innerWidth);
console.log(window.innerHeight);
}, 250)
); // Will log the window dimensions at most every 250ms