The normal debounce approach is
let resizeDebounceTimer: number = 0;
window.addEventListener('resize', () => {
clearTimeout(resizeDebounceTimer);
resizeDebounceTimer = setTimeout(windowResize, 100);
});
The problem with that is that this will run always with a 100ms pause.
You often instead want the following pattern:
- Run the debounced function immediately
- when the event fires again within 100ms do nothing
- when the event fires again after 100ms have passed since the last firing call the function - again this is now immediately on event
- run the function in any case at the next 100ms again
Thats called THROTTLING not debouncing!
function throttle(fn: () => void, interval: number) {
let lastTime = 0;
let timer: number | null = null;
return () => {
const now = performance.now();
const remaining = interval - (now - lastTime);
// 1. If interval has passed (or first call), run immediately
if (remaining <= 0 || remaining > interval) {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
lastTime = now;
fn();
}
// 2. Otherwise schedule trailing run to hit the exact boundary
else if (timer === null) {
timer = setTimeout(() => {
lastTime = performance.now();
timer = null;
fn();
}, remaining);
}
};
}
with AbortController Support
/** this runs a function immediately or at the next exact boundary
* The function thus will run in ANY case as fast as possible or at end of the next interval
*/
export function throttle(fn: () => void, interval: number, signal?: AbortSignal) {
let lastTime = 0;
let timer: number | null = null;
// abortController functions
const cleanupTimer = () => {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
};
const abort = () => {
cleanupTimer();
}
// fast return
// this is just a catch whether you made a throttle function while this when signal was already aborted,
// i doubt this ever happens
if (signal?.aborted) {
return () => { };
}
signal?.addEventListener("abort", abort, { once: true });
return () => {
// fast return
if (signal?.aborted) return;
const now = performance.now();
const remaining = interval - (now - lastTime);
// 1. If interval has passed (or first call), run immediately
if (remaining <= 0 || remaining > interval) {
// it can happen that the delayed timer has not run yet although we executed the throttled function after the delay passed again.
// then you need to cleanup still.
cleanupTimer();
lastTime = now;
fn();
}
// 2. Otherwise schedule trailing run to hit the exact boundary
else if (timer === null) {
timer = setTimeout(() => {
timer = null;
if (signal?.aborted) return;
lastTime = performance.now();
fn();
}, remaining);
}
};
}