In JavaScript, you can make code run again and again at regular time intervals using the setInterval()
method. It’s perfect for tasks like updating a clock, refreshing data, or running animations.
In this article, you'll learn how to use setInterval()
, see real examples, and understand how to stop it when needed.
What is setInterval()
?
The setInterval()
function repeatedly calls a function or runs a block of code every few milliseconds, until it's stopped.
Syntax:
-
function
: The code you want to run repeatedly (usually a function). -
interval
: Time between runs, in milliseconds (1000 ms = 1 second).
Example: Display the Time Every Second
What it does:
This shows the current time and updates it every second, like a live clock.
Common Use Cases for setInterval()
-
Creating a live clock or countdown timer
-
Polling the server for updates (e.g. checking messages)
-
Rotating images in a slideshow
-
Animating elements repeatedly
Example: Change Text Every 2 Seconds
How to Stop setInterval()
To stop the repeated code, use clearInterval()
with an ID.
Example:
Things to Know
-
setInterval()
is asynchronous — it doesn’t block other code. -
If your code inside
setInterval()
takes too long, it might overlap. -
Always use
clearInterval()
when you no longer need it — especially in loops or dynamic pages.
Summary
The setInterval()
function helps you run code over and over at a set interval. It’s useful for clocks, timers, animations, and auto-updating UI elements.
Key Takeaways:
-
Repeats code at regular intervals
-
Time is in milliseconds
-
Use
clearInterval()
to stop it -
Great for real-time updates and repeated tasks