A throttle you can test with a fake clock
With real timers the exact numbers would wobble by a few milliseconds. A fake clock makes the behaviour exact, which is how test libraries (such as Jest's and Vitest's fake timers) test debounce and throttle.
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.
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.
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
Explain debounce and throttle, and give one use case for each.
Implement a debounce(fn, delay) function and explain how it works.
Why is the debounced function usually created once, outside the event listener?
When would you use requestAnimationFrame instead of a time-based throttle?
Preview
Console
Nothing logged yet.Expected console output
handled at 0 ms, scrollY = 0
handled at 100 ms, scrollY = 200
handled at 200 ms, scrollY = 400
handled at 300 ms, scrollY = 600
13 events, 4 handled