Show contents
Chapter 4 of 6 · 20 min
Performance: less work, less waiting
By the end of this chapter, you'll be able to
- Limit the calls triggered by typing with a debounce
- Limit how often a handler runs with a throttle
- Avoid repeated computations with memoization
- Reduce a page's weight and loading time
Debounce: wait until the user has finished
A search-as-you-type that queries the server on every key sends five requests to type "dakar", four of them useless. A debounce waits until the user pauses before acting: each new call cancels the previous one.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function debounce(fn, delayMs) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delayMs);
};
}
const search = (text) => console.log(`request sent: "${text}"`);
const searchLater = debounce(search, 150);
// The user types "dakar", one key every 50 ms, then pauses.
for (const text of ["d", "da", "dak", "daka", "dakar"]) {
searchLater(text);
await wait(50);
}
await wait(300);
searchLater("dakar beach");
await wait(300);
request sent: "dakar"
request sent: "dakar beach"
A single request, with the full text, instead of five.
Text description of the animation
- First key: a 150 ms timer starts.
- 50 ms later, second key: the previous timer is cancelled, a new one starts.
- The same on each key: no search goes out while typing.
- The user stops: the last timer runs out.
- A single request, with the full text, instead of five.
Throttle: at most once per interval
For a continuous event such as scrolling or resizing, waiting for the end isn't suitable: you want regular updates, but not sixty per second. A throttle runs at most once per interval, and guarantees that the last value is handled. You'll write it in the exercise.
For scrolling, the browser often offers better: IntersectionObserver tells you when an element enters the screen, without listening to every movement.
Memoization: don't recompute
A pure function called several times with the same arguments always returns the same result: you can remember it. That's memoization:
let computations = 0;
function distanceKm([lat1, lon1], [lat2, lon2]) {
computations += 1;
const rad = Math.PI / 180;
const a = Math.sin(((lat2 - lat1) * rad) / 2) ** 2 + Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * Math.sin(((lon2 - lon1) * rad) / 2) ** 2;
return Math.round(2 * 6371 * Math.asin(Math.sqrt(a)));
}
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (!cache.has(key)) cache.set(key, fn(...args));
return cache.get(key);
};
}
const distance = memoize(distanceKm);
const dakar = [14.69, -17.44], bamako = [12.64, -8.0], abidjan = [5.36, -4.01];
for (let i = 0; i < 1000; i++) {
distance(dakar, bamako);
distance(bamako, abidjan);
}
console.log(distance(dakar, bamako), "km and", distance(bamako, abidjan), "km");
console.log("real computations:", computations, "out of 2002 calls");
1045 km and 920 km
real computations: 2 out of 2002 calls
The cache key is JSON.stringify(args): simple, but limited to serialisable arguments. And a cache without a limit grows forever: for very varied arguments, keep only the last N entries.
Loading the page
The fastest code is the code you don't download. A few rules that matter on a slow network:
<!-- Images: modern format, suitable size, deferred loading off-screen -->
<img src="workshop-800.avif" srcset="workshop-400.avif 400w, workshop-800.avif 800w"
sizes="(max-width: 600px) 100vw, 800px" width="800" height="450"
loading="lazy" alt="The cooperative's sewing workshop">
<!-- Scripts: as a module (deferred by default), without blocking display -->
<script type="module" src="app.js"></script>
widthandheightreserve the image's space: the page doesn't "jump" while loading.loading="lazy"only loads the image when it gets close to the screen. Don't use it for the main image at the top of the page, which you want as soon as possible.- Load on demand what isn't needed right away:
const { openMap } = await import("./map.js");only downloads the map module on click. - Measure before optimising: the browser dev tools' Performance tab and the Core Web Vitals (LCP, INP, CLS) show where the real problem is. Test with slow-network simulation.
Your turn
Mini-lab: memoizing a costly conversionJavaScript
Output
Click “Run” to execute your code.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: throttling the scroll
Write throttle(fn, intervalMs), which returns a version of fn run at most once per interval. The first call runs immediately; calls that come too close together are grouped, and the last of them runs at the end of the interval, so the final position is never lost. Simulate scrolling from 0 to 1,000 pixels in steps of 50, every 25 ms.
Hint 1
Date.now()). If the interval has elapsed, run straight away.Hint 2
Show the solution and common mistakes
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function throttle(fn, intervalMs) {
let last = -Infinity;
let pending = null;
return (...args) => {
const now = Date.now();
if (now - last >= intervalMs) {
last = now;
fn(...args);
} else {
clearTimeout(pending);
pending = setTimeout(() => {
last = Date.now();
fn(...args);
}, intervalMs - (now - last));
}
};
}
const positions = [];
const record = throttle((y) => positions.push(y), 200);
for (let y = 0; y <= 1000; y += 50) {
record(y);
await wait(25);
}
await wait(300);
console.log("far fewer than 21 updates:", positions.length < 8);
console.log("first:", positions[0], "last:", positions.at(-1));
far fewer than 21 updates: true
first: 0 last: 1000
The exact number of updates depends on the machine's timing, hence the < 8 test rather than a precise figure. What matters: the first position (0) goes out immediately, the last (1,000) is never lost, and the costly handler only runs a few times.
Common mistakes:
- Simply ignoring calls that come too close together, with no delayed run: if scrolling stops just after an update, the final position is never handled and the display stays wrong.
- Confusing throttle and debounce: with a debounce, nothing would happen during scrolling, only at the end.
Summary
- 1A debounce waits for a pause before acting: ideal for search-as-you-type.
- 2A throttle runs at most once per interval, without losing the last value.
- 3Memoization avoids recomputing a pure function with the same arguments.
- 4Create the debounce or throttle once, outside the event handler.
- 5Suitable, deferred images, code loaded on demand, measurements on slow networks: performance is a matter of access.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.