← All lessons
How debounce and throttle work
Five keys, three ways to search
search.js
const input = document.querySelector("#search"); // every keystroke sends a requestinput.addEventListener("input", (e) => { search(e.target.value);}); // one request, once typing pauses for 300 msconst searchLater = debounce(search, 300);input.addEventListener("input", (e) => { searchLater(e.target.value);}); // at most one request every 300 msconst searchSteady = throttle(search, 300);input.addEventListener("input", (e) => { searchSteady(e.target.value);});debounce.js
function debounce(fn, wait) { let timer; return (...args) => { clearTimeout(timer); // a new call cancels the waiting one timer = setTimeout(() => { fn(...args); // runs after wait ms with no new call }, wait); };}Type and watch the calls debounce and throttle side by side
The last few seconds
input 0
debounce 0
throttle 0
debounce sent
throttle sent
A long wait makes search feel laggy. 200 to 300 ms suits typing
throttle.js
function throttle(fn, wait) { let last = -Infinity; let timer = null; let pending; return (...args) => { const left = wait - (Date.now() - last); if (left <= 0 && !timer) { last = Date.now(); fn(...args); // window open: run now return; } pending = args; // inside the window: keep the newest args timer ??= setTimeout(() => { timer = null; last = Date.now(); fn(...pending); // window ends: run once with them }, left); };}Scroll a long feed and count what the handler runs
- #1Post 1
- #2Post 2
- #3Post 3
- #4Post 4
- #5Post 5
- #6Post 6
- #7Post 7
- #8Post 8
- #9Post 9
- #10Post 10
- #11Post 11
- #12Post 12
- #13Post 13
- #14Post 14
- #15Post 15
- #16Post 16
- #17Post 17
- #18Post 18
- #19Post 19
- #20Post 20
- #21Post 21
- #22Post 22
- #23Post 23
- #24Post 24
- #25Post 25
- #26Post 26
- #27Post 27
- #28Post 28
- #29Post 29
- #30Post 30
- #31Post 31
- #32Post 32
- #33Post 33
- #34Post 34
- #35Post 35
- #36Post 36
- #37Post 37
- #38Post 38
- #39Post 39
- #40Post 40
scroll events0
throttled0
scroll ended0
handler saw
Leading only drops the calls inside each window, so it can miss where the scroll stopped
scroll.js
const feed = document.querySelector(".feed");const update = () => setProgress(feed.scrollTop); // while scrolling: at most once per 100 msconst onScroll = throttle(update, 100); // once scrolling stops for 200 msconst onScrollEnd = debounce(() => { savePosition(feed.scrollTop);}, 200); feed.addEventListener("scroll", () => { onScroll(); onScrollEnd();}, { passive: true });scroll.js
const feed = document.querySelector(".feed");const update = () => setProgress(feed.scrollTop); // no trailing call, so calls inside the window are droppedconst onScroll = throttle(update, 100, { trailing: false }); // once scrolling stops for 200 msconst onScrollEnd = debounce(() => { savePosition(feed.scrollTop);}, 200); feed.addEventListener("scroll", () => { onScroll(); onScrollEnd();}, { passive: true });Topics
Next: How Web Workers work
Open lesson