Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.7 — Debounce and Throttle
JavaScript · Example 1 of 3

A debounced search box

Three input events, one search, 300 ms after the last letter. Type in the box yourself: pause, then type fast, and count the searches.

Some events fire dozens of times a second (typing, scrolling, resizing). Debounce waits until the events stop for a moment and then runs once; throttle runs at most once per time window while they keep coming. Both are small functions built from closures and timers.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Debounce an "autosave" so it logs saved: <text> 500 ms after the user stops typing in a <textarea id="note">. Simulate two quick input events.

02

Write a once(fn) helper (a close cousin of these) that runs fn the first time and returns the first result on every later call.

Explain it without notes

01

Explain debounce and throttle, and give one use case for each.

02

Implement a debounce(fn, delay) function and explain how it works.

03

Why is the debounced function usually created once, outside the event listener?

04

When would you use requestAnimationFrame instead of a time-based throttle?

A debounced search box

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

input: m
input: ma
input: man
search #1 for "man" -> [ 'mango', 'mangosteen' ]