setTimeout
Overview
The setTimeout() method calls a function after a specified number of milliseconds. It is the simplest form of asynchronous programming in JavaScript.
It is crucial to understand that the time you specify is the minimum delay, not a guaranteed exact delay. If the Call Stack is busy doing heavy synchronous work, the timeout callback will be delayed until the stack clears.
Syntax
// setTimeout(callback, delayInMilliseconds)
setTimeout(() => {
console.log("This prints after 2 seconds.");
}, 2000);// setTimeout returns a unique ID
const timerId = setTimeout(() => {
console.log("You will never see this.");
}, 5000);
// If the user clicks 'cancel' before 5s, we can stop it!
clearTimeout(timerId);Common Pitfalls
- Running
setTimeout(..., 0). Beginners often think this executes the code instantly. It does NOT. It pushes the callback into the Web API queue, meaning it will execute after all current synchronous code finishes, effectively moving it to the back of the line.
Interview Questions
setTimeout(myFunc, 0) do?It defers the execution of myFunc until the current call stack is completely empty. It is often used to yield rendering control back to the browser briefly so the UI doesn't freeze during heavy operations.
Real-World Example
Implementing a 'Debounce' function for a search bar. We don't want to hit the API on every single keystroke. We use setTimeout to wait 500ms after the user stops typing before making the request.
let timeout;
input.addEventListener('keyup', () => {
clearTimeout(timeout);
timeout = setTimeout(searchDatabase, 500);
});Check Your Knowledge
Test your understanding of setTimeout with these quick questions.