Sub topic 3
Adding cancel and flush
This chapter assumes you have already built the trailing-edge debounce and the timestamp throttle from the earlier chapters. You should also be comfortable with closures, setTimeout, and Function.prototype.apply.
Adding cancel and flush
A debounced function holds a pending call. Sometimes you need to control that call from outside:
cancelthrows away the pending call. Use it when a component unmounts.flushruns the pending call right away. Use it to save a draft before the page closes.
function debounce(fn, wait) {
let timerId;
let lastThis;
let lastArgs;
function invoke() {
const ctx = lastThis;
const args = lastArgs;
timerId = undefined;
lastThis = undefined;
lastArgs = undefined;
return fn.apply(ctx, args);
}
function debounced(...args) {
lastThis = this;
lastArgs = args;
clearTimeout(timerId);
timerId = setTimeout(invoke, wait);
}
debounced.cancel = function () {
clearTimeout(timerId);
timerId = undefined;
lastThis = undefined;
lastArgs = undefined;
};
debounced.flush = function () {
if (timerId !== undefined) {
clearTimeout(timerId);
return invoke();
}
};
return debounced;
}Bounding the Wait with maxWait
If a user types without stopping, a plain debounce never fires. The maxWait option forces a call once that much time has passed since the first call in a burst. With maxWait, debounce behaves like a throttle during long bursts and like a debounce during short ones.
Frame-Based Throttling with requestAnimationFrame
For visual updates, a fixed millisecond wait is a guess. requestAnimationFrame runs the update at most once per frame, at the same rate the browser paints:
function rafThrottle(fn) {
let frameId = null;
let lastArgs;
return function (...args) {
lastArgs = args;
if (frameId === null) {
frameId = requestAnimationFrame(() => {
frameId = null;
fn.apply(this, lastArgs);
});
}
};
}Testing Timing Code with Fake Timers
Real delays make tests slow and flaky. Jest fake timers let you move the clock forward yourself:
jest.useFakeTimers();
test('debounced function runs once after the wait', () => {
const fn = jest.fn();
const debounced = debounce(fn, 100);
debounced('a');
debounced('b');
debounced('c');
expect(fn).not.toHaveBeenCalled();
jest.advanceTimersByTime(100);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith('c');
});Using Lodash debounce and throttle in Production
Lodash's versions are well tested and support leading, trailing, maxWait, cancel, and flush:
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';
const saveDraft = debounce(() => console.log('Saving draft'), 1000, { maxWait: 5000 });
const onResize = throttle(() => console.log('Width:', window.innerWidth), 250);
window.addEventListener('resize', onResize);
window.addEventListener('beforeunload', () => saveDraft.flush());Debouncing in React Without Common Pitfalls
React runs your component function again on every render. If you call debounce directly in the body, each render creates a new timer, so the debounce never takes effect. Use useMemo to keep one instance, and cancel it during cleanup:
import { useEffect, useMemo, useState } from 'react';
import debounce from 'lodash/debounce';
function SearchBox({ onSearch }) {
const [text, setText] = useState('');
const debouncedSearch = useMemo(() => debounce((q) => onSearch(q), 300), [onSearch]);
useEffect(() => () => debouncedSearch.cancel(), [debouncedSearch]);
return (
<input
value={text}
onChange={(e) => {
setText(e.target.value);
debouncedSearch(e.target.value);
}}
/>
);
}Exercise
A user types continuously for 10 seconds into a field debounced with wait 1000 and maxWait 3000. Roughly how many times does the handler run?
Show answer
About four times. maxWait forces calls at roughly 3, 6, and 9 seconds, then the trailing call runs 1 second after typing stops.