Sometimes in JavaScript, you may want to pause or delay code execution for a few seconds. The easiest way to do this is by using the built-in setTimeout()
function. This method allows you to run a piece of code after a specific amount of time has passed.
In this article, we’ll explain how setTimeout()
works, give real examples, and cover common use cases.
What is setTimeout()
?
The setTimeout()
function lets you run code after a delay, measured in milliseconds.
Syntax:
-
function
: The code you want to run later (usually a function). -
delay
: Time to wait in milliseconds (1 second = 1000 milliseconds).
Example: Basic Usage
What happens:
When you click the button, the alert appears 2 seconds later.
Common Use Cases for setTimeout()
-
Delay showing a message or modal
-
Wait before redirecting the user
-
Add pause between animations
-
Delay an action after form submission
Example: Delayed Redirect
What it does:
Shows a message, waits 3 seconds, then takes the user to a new URL.
Things to Keep in Mind
-
The delay is not exact. It waits at least the specified time, but not always exactly.
-
setTimeout()
is asynchronous, meaning the rest of your code continues to run while it waits. -
You can cancel a timeout using
clearTimeout()
if needed.
Bonus: Cancel a setTimeout
Summary
The setTimeout()
method is a powerful tool in JavaScript to delay code execution. Whether you're waiting before showing a message, starting an animation, or redirecting users, it’s one of the most useful timing functions in JavaScript.
Key Points:
-
Delays code using milliseconds
-
Runs code only once after the delay
-
Can be canceled with
clearTimeout()
-
Ideal for popups, redirects, and timed effects