Sub topic 1
Why Some Events Fire Too Often
Some browser events fire dozens or hundreds of times per second. If each one runs an expensive handler, the page slows down, the network fills with requests, and the user sees stutter. This chapter explains which events cause the problem and how to measure it. The rest of the tutorial builds the fixes.
Prerequisites
This chapter assumes you already know:
- JavaScript functions and arrow functions
- Closures and lexical scope
setTimeoutandclearTimeout- DOM event listeners (
addEventListener) - The basics of the event loop
- Rest parameters (
...args) andFunction.prototype.apply
You won't need closures and timers until the later chapters, but this chapter's examples use event listeners throughout.
The High-Frequency Events
A high-frequency event is one the browser can dispatch many times during a single user action. The common ones are listed below.
| Event | What triggers it | Typical rate |
|---|---|---|
| `input` | Each keystroke, paste, or deletion in a field | Once per character |
| `scroll` | Scrolling a page or element | Up to once per frame (about 60/s) |
| `resize` | Dragging the window edge | Up to once per frame |
| `pointermove` / `mousemove` | Moving the pointer | 60/s or more; high-refresh displays send more |
A single swipe on a trackpad can produce 30 to 100 scroll events. If you type "javascript", the field fires input ten times.
Measuring It Yourself
Paste this into the console of any long page and scroll around:
let count = 0;
window.addEventListener('scroll', () => {
count++;
});
setInterval(() => {
if (count > 0) {
console.log(`scroll events in the last second: ${count}`);
}
count = 0;
}, 1000);You will usually see numbers between 30 and 120 while you scroll. Change 'scroll' to 'pointermove' and move the mouse to compare.
Why This Hurts
The events cost almost nothing to fire. The handlers attached to them are what get expensive. Three kinds of work cause trouble:
- Network requests. A search box that calls an API on every
inputsends one request per keystroke. Most of those responses are out of date before they arrive, and they can come back out of order. - Layout and rendering. A handler that reads layout values such as
offsetHeightorgetBoundingClientRect()and then writes styles can force the browser to recalculate layout many times per frame. - Heavy computation. Filtering a large list or redrawing a chart on every
resizeblocks the main thread, so the page stops responding to input.
The Core Idea: Run the Handler Less Often
Usually the handler doesn't need to see every event. It needs one of two things:
- The final state after activity stops. A search box only cares about what the user typed once they pause. This is called debouncing.
- Regular updates while activity continues. A scroll-position indicator should update steadily as the user scrolls, but 10 updates per second is enough. This is called throttling.
Both techniques wrap your handler in another function that decides when the real handler runs. Neither one changes how often the browser fires events.
Common Mistakes
- Assuming
resizefires once at the end of a drag. It fires throughout the drag. - Testing on a fast laptop only. A handler that takes 5 ms is fine at 60 events per second there and causes jank on a low-end phone.
- Firing a network request per keystroke and showing whichever response arrives last. That response may belong to an older query.
Exercise
A page redraws a chart inside a resize handler, and each redraw takes 20 ms. The user drags the window edge for 2 seconds, and resize fires about 60 times per second. Roughly how much main-thread time goes to redraws, and which technique fits if the chart only needs to look right once the drag ends?
Show answer
About 120 redraws at 20 ms each, so roughly 2,400 ms of work requested in 2 seconds. That is more than the main thread can handle, so the page will stutter. Debouncing fits because only the final size matters: the chart redraws once after the user stops resizing.
Exercise
A reading-progress bar at the top of an article must update while the user scrolls. Should you debounce or throttle the scroll handler, and why?
Show answer
Throttle it. The bar needs regular updates during the scroll. A debounced handler would update only after scrolling stops, so the bar would freeze and then jump.