If you’ve ever written JavaScript and wondered why certain things happen out of order, a log shows up late, an event fires too early, you're not alone. One of the simplest and most useful tools to help make sense of this is setTimeout
.
In this post, we’ll look at what setTimeout
is, when you’d use it, and some common mistakes to avoid.
Want the full deep-dive? Check out the complete version on the ZTM blog for more detailed examples and advanced use cases.
What is setTimeout
?
setTimeout
is a built-in JavaScript function that lets you schedule code to run after a delay (in milliseconds). Instead of freezing the entire program, it lets your code continue running while the callback is queued up to execute later.
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
Even a delay of 0
milliseconds doesn’t run immediately. JavaScript finishes its current tasks first, then checks the timeout queue — this is thanks to the event loop. It’s a great way to see JavaScript’s asynchronous nature in action.
When You Might Use It
setTimeout
comes in handy for a bunch of real-world scenarios like:
- Delaying a tooltip or message
- Waiting before retrying a failed request
- Deferring heavy logic until after a UI update
- Creating animations with slight delays
Example: Show a quick confirmation message after a button click:
button.addEventListener("click", () => {
message.innerText = "Saved!";
setTimeout(() => {
message.innerText = "";
}, 1500);
});
It’s not a performance hack — it won’t speed up your page — but it can make things feel smoother by giving the browser time to render changes before heavier operations kick in.
How to Cancel a setTimeout
You can cancel a timeout before it fires by using clearTimeout
. First, you’ll need to store the timeout ID returned by setTimeout
.
const timeoutId = setTimeout(() => {
console.log("This will never run");
}, 3000);
clearTimeout(timeoutId);
This is especially useful in interactive UI elements — like canceling a tooltip that shouldn’t appear if the user moves their mouse away quickly:
let tooltipTimeout;
button.addEventListener("mouseenter", () => {
tooltipTimeout = setTimeout(() => {
showTooltip();
}, 500);
});
button.addEventListener("mouseleave", () => {
clearTimeout(tooltipTimeout);
});
Common Pitfalls to Avoid
Even though setTimeout
is simple to use, it trips up beginners in a few key ways:
- Calling the function too early Don’t use parentheses when passing your function:
setTimeout(doSomething, 2000); // ✅ correct
Not storing the ID If there’s even a small chance you’ll want to cancel the timeout, save the ID.
Thinking it blocks code It doesn’t wait like a
sleep()
function, it schedules the code and immediately continues.Using it for loops Want to delay actions one after another? Use recursion instead:
let i = 0;
function logNext() {
if (i < 5) {
console.log(i++);
setTimeout(logNext, 1000);
}
}
logNext();
Try It Yourself
Playing around with setTimeout
is one of the best ways to better understand how JavaScript handles time and asynchronous operations.
Want more examples, advanced tips, and best practices? Read the full guide here →
Top comments (0)