Sub topic 1
Why Some Events Fire Too Often
Some browser events fire once per user action. A click, for example, gives you one click event. Other events fire continuously while the user does something. Dragging a window edge, scrolling a page, moving the mouse, or typing a word can produce dozens or hundreds of events in a few seconds. If each event runs expensive work, the page slows down, the network fills with requests, and results can arrive in the wrong order.
This chapter explains which events behave this way, how often they fire, and what goes wrong when a handler runs on every one. Later chapters build the tools that fix it.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions and arrow functions
- Closures and lexical scope
setTimeoutandclearTimeout- DOM event listeners (
addEventListener) - The basic event loop: one main thread runs your handlers, rendering, and input processing in turns
- Rest parameters (
...args) andFunction.prototype.apply
You do not need to know debouncing or throttling yet. That is the subject of this tutorial.
What Makes an Event "High-Frequency"
A high-frequency event is one the browser dispatches repeatedly during a single, continuous user gesture. The user experiences the gesture as one thing ("I scrolled down"), but your code receives it as a stream of separate events.
The common ones are:
| Event | Fires when | Typical rate during the gesture | Work handlers often do |
|---|---|---|---|
| `input` | The value of a text field changes | One per keystroke, about 5–10 per second for normal typing and up to about 30 with key repeat | Search requests, validation, autosave |
| `keydown` | A key is pressed or auto-repeats | Same as above | Shortcuts, live previews |
| `scroll` | A scroll container's position changes | Up to once per rendered frame: about 60 per second on a 60 Hz screen, 120 on a 120 Hz screen | Sticky headers, lazy loading, progress bars |
| `resize` | The viewport size changes | Up to once per frame while the user drags | Layout recalculation, chart redraws |
| `pointermove` / `mousemove` | The pointer moves | Usually about once per frame, and more often with high-polling mice in some setups | Drag and drop, tooltips, drawing |
| `wheel` | The wheel or trackpad scrolls | Many per second, especially with trackpad momentum | Custom zoom, custom scrolling |
| `touchmove` | A finger moves on a touchscreen | About once per frame | Swipe gestures, pull to refresh |
The exact rates depend on the browser, the device, and the display. Current browsers align scroll, resize, and usually pointermove with the rendering cycle, so they fire at most about once per frame. That limit is still far higher than most handlers need. A handler that runs 120 times per second gets about 8 ms each time, and it shares that time with everything else the page does in the same frame.
Measure It Yourself
You will see the scale of the problem more clearly if you count the events yourself. Paste this into the browser console on any page with a scrollable area and a text field. You can also save it as a script in an HTML page that has an <input> element.
const counts = { input: 0, scroll: 0, resize: 0, pointermove: 0 };
for (const type of Object.keys(counts)) {
// input bubbles, so listening on document catches every text field
const target = type === 'input' ? document : window;
target.addEventListener(type, () => {
counts[type] += 1;
}, { passive: true });
}
setInterval(() => {
const active = Object.entries(counts).filter(([, n]) => n > 0);
if (active.length > 0) {
console.table(Object.fromEntries(active));
}
for (const type of Object.keys(counts)) {
counts[type] = 0;
}
}, 1000);Move the mouse in circles, scroll quickly, drag the window edge, and type into a field. Each second, the console prints how many events of each type arrived. Pointer and scroll counts commonly land between 60 and 120 per second. Resizing the window can produce similar numbers. Each of those events would have run your handler.
What Goes Wrong When Every Event Runs the Handler
Running a cheap handler, like incrementing a counter, on every event is fine. The problems start when the handler does real work.
Main-thread jank
JavaScript handlers, style calculation, layout, and painting all run on the main thread. If a scroll handler takes 20 ms and fires 60 times per second, it needs 1.2 seconds of work for every second of scrolling. The browser can't keep up, so it drops frames and the page stutters. Users call this jank.
Layout reads make it worse. A handler that reads element.offsetHeight or getBoundingClientRect() right after changing styles forces the browser to recalculate layout synchronously. Doing that on every scroll or resize event is one of the most common causes of slow pages.
Wasted network requests
A search box that sends a request on every input event sends one request per character. Typing "javascript" sends ten requests, and only the last one matters. This wastes bandwidth and server capacity, and on metered APIs it costs money.
Out-of-order results
Network responses don't arrive in the order you sent the requests. An early, short query like "j" can match more records and respond more slowly than the later query "javascript". If each response renders when it arrives, the screen can end up showing results for an old query.
This Node.js simulation shows both problems. Run it with node search-sim.js:
function fakeSearch(query) {
const latency = 100 + Math.random() * 400; // 100–500 ms, like a real network
return new Promise((resolve) => {
setTimeout(() => resolve(`results for "${query}"`), latency);
});
}
let requests = 0;
function onInput(value) {
requests += 1;
fakeSearch(value).then((result) => {
console.log(`render: ${result}`);
});
}
// Simulate typing "react" with 50 ms between keystrokes
const word = 'react';
for (let i = 0; i < word.length; i += 1) {
setTimeout(() => onInput(word.slice(0, i + 1)), i * 50);
}
setTimeout(() => {
console.log(`requests sent: ${requests}`);
}, 1000);Run it a few times. It always sends five requests. The render: lines often appear in a shuffled order, and the last line rendered is not always results for "react". In a real UI, that last render is what the user sees.
Battery and memory
Every handler call costs CPU time. On phones and laptops, wasted work drains the battery. Handlers that allocate objects on every call, such as building arrays or formatting strings, also create garbage that the engine must collect, which can cause pauses of its own.
The Shape of the Problem
The diagram shows what happens without any rate limiting. One gesture becomes many events, and each event runs the full handler.
Two Strategies, Previewed
You can reduce the number of handler runs in two main ways. Later chapters build both from scratch.
- Debouncing waits until the events stop. The handler runs once, after a quiet period. This fits the search box: you care about the final text, not each keystroke.
- Throttling sets a maximum rate. The handler runs at most once per interval while events keep coming. This fits a scroll progress bar: it should update while the user scrolls, just not 120 times per second.
Both strategies wrap your handler in another function. The wrapper uses a closure to remember timer and timestamp state between calls. The next chapter covers those building blocks.
Before You Reach for Rate Limiting
Sometimes the better fix is to avoid the event entirely. The browser has built-in tools that do the work for you more efficiently:
| Goal | Instead of listening to | Consider |
|---|---|---|
| Detect when an element enters the viewport | `scroll` | `IntersectionObserver` |
| React to an element's size changing | `resize` | `ResizeObserver` |
| Sticky headers, scroll-linked visuals | `scroll` | CSS `position: sticky`, scroll-driven animations |
| Smooth visual updates tied to movement | raw `pointermove` work | Updating once per frame with `requestAnimationFrame` (covered later) |
These alternatives don't cover every case. Search-as-you-type, autosave, analytics on scroll depth, and window-size-dependent logic still need debounce or throttle.
Common Misconceptions
- "Passive listeners fix scroll performance."
{ passive: true }tells the browser your handler won't callpreventDefault(), so scrolling doesn't wait on your code. Your handler still runs on every event, and it still costs main-thread time. - "Scroll fires once per pixel." Browsers dispatch
scrollat most about once per frame. The rate is still high, but tying a handler to exact pixel positions is a mistake. - "Typing is too slow to matter." Ten requests per word adds up across many users, and it causes the ordering bugs shown earlier.
- "The browser rate-limits events for me." The browser limits events to the frame rate, which is too fast for network calls and heavy computation.
Exercise
A page attaches a scroll handler that calls getBoundingClientRect() on 50 elements and updates their classes. On a 120 Hz display, roughly how many times per second can this handler run during a fast scroll, and why does that hurt performance?
Show answer
About 120 times per second, because current browsers dispatch scroll up to once per rendered frame. Each run reads layout for 50 elements and then writes classes. Mixing reads and writes can force synchronous layout recalculation, and at 120 runs per second that work can exceed the roughly 8 ms frame budget, which drops frames and causes jank.
Exercise
In the search simulation, why is the final rendered result sometimes for "rea" instead of "react", and would sending fewer requests fully solve this?
Show answer
Each request has random latency, so a request for an earlier query can finish after the request for "react" and overwrite its result on screen. Sending fewer requests makes this less likely but does not remove it, because any two overlapping requests can still finish out of order. You also need to ignore stale responses, for example by aborting old requests or checking a request ID.
Exercise
For each case, say whether debouncing, throttling, or a built-in browser API is the best first choice: (a) lazy-loading images as they scroll into view, (b) validating a username field against the server, (c) updating a reading-progress bar while scrolling.
Show answer
(a) A built-in API: IntersectionObserver detects visibility without a scroll listener. (b) Debouncing, because only the final value after the user pauses matters. (c) Throttling, because the bar should update steadily during the scroll at a limited rate.