QJavaScript · Interview preparation
Does setTimeout(callback, 0) run immediately?
No.
The idea to remember.
No. The callback is scheduled for a later task after the current stack and queued microtasks have finished. Actual timing also depends on browser scheduling and timer clamping.
01Learn by doing
From first example to real project.
Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.
Basic: debounce after typing
01 / BEGINNERDelay work until the user stops typing.
function debounce(fn, wait) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}Intermediate: throttle frequent events
02 / INTERMEDIATERun periodic updates instead of handling every scroll event.
function throttle(fn, wait) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= wait) { last = now; fn(...args); }
};
}Real scenario: autocomplete input
03 / REAL SCENARIODebounce API work and encode user input safely.
const suggest = debounce(async term => {
const response = await fetch('/api/suggest?q=' + encodeURIComponent(term));
if (!response.ok) return;
showSuggestions(await response.json());
}, 250);02Check your understanding
Try it in your own words.
Explain does setTimeout(callback, 0) run immediately without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.
Keep learning here.
Explore more in-depth guides, exercises and related interview questions in this library.
Browse JavaScript study guides ↗