Belajar
← 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

Search products
Wait300 ms
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

Throttle every 100 msLeading + trailingLeading only
  1. #1Post 1
  2. #2Post 2
  3. #3Post 3
  4. #4Post 4
  5. #5Post 5
  6. #6Post 6
  7. #7Post 7
  8. #8Post 8
  9. #9Post 9
  10. #10Post 10
  11. #11Post 11
  12. #12Post 12
  13. #13Post 13
  14. #14Post 14
  15. #15Post 15
  16. #16Post 16
  17. #17Post 17
  18. #18Post 18
  19. #19Post 19
  20. #20Post 20
  21. #21Post 21
  22. #22Post 22
  23. #23Post 23
  24. #24Post 24
  25. #25Post 25
  26. #26Post 26
  27. #27Post 27
  28. #28Post 28
  29. #29Post 29
  30. #30Post 30
  31. #31Post 31
  32. #32Post 32
  33. #33Post 33
  34. #34Post 34
  35. #35Post 35
  36. #36Post 36
  37. #37Post 37
  38. #38Post 38
  39. #39Post 39
  40. #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 });

Topics

Next: How Web Workers work

Open lesson