Timers, Intervals & Debouncing
Schedule delayed or recurring work with setTimeout and setInterval, clean up timers properly, and debounce rapid user input.
What you'll learn
- Schedule one-shot delays with setTimeout() and cancel them with clearTimeout()
- Build a start/stop timer with setInterval() and clearInterval()
- Implement a reusable debounce() helper for search inputs
Timers let you coordinate delayed notifications, countdowns, and performance optimizations like debouncing.
Debouncing Rapid Input
When a user types "javascript" into a search bar, firing an API request on all 10 keystrokes wastes bandwidth. A debounce waits until the user pauses typing for 300ms:
function debounce(fn, delayMs = 300) {
let timerId;
return (...args) => {
clearTimeout(timerId);
timerId = setTimeout(() => fn(...args), delayMs);
};
}
Fill-in-the-Blank Exercise
Cancel Previous Timer (Debounce)
Cancel any pending timer before scheduling a new delayed call.
let timer;
function runDebounced(fn) {
(timer);
timer = (fn, 300);
}Try It Yourself
Type quickly into the input below and compare the Raw keystrokes count vs. the Debounced API calls count!
No console output yet. Try calling console.log(...) in JS.
Check Your Understanding
1. What does debouncing a search input accomplish?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.