Run Code Repeatedly with setInterval

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:

    setInterval(function, interval);
  • 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

    <p id="clock"></p>

    <script>
    setInterval(() => {
    const now = new Date();
    document.getElementById("clock").innerText = now.toLocaleTimeString();
    }, 1000); // updates every 1 second
    </script>

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

    <p id="message">Waiting...</p>

    <script>
    const messages = ["Loading...", "Still working...", "Almost done!"];
    let index = 0;

    setInterval(() => {
    document.getElementById("message").innerText = messages[index];
    index = (index + 1) % messages.length;
    }, 2000); // every 2 seconds
    </script>

How to Stop setInterval()

To stop the repeated code, use clearInterval() with an ID.

Example:

    let timerId = setInterval(() => {
    console.log("Running every second");
    }, 1000);

    // Stop it after 5 seconds
    setTimeout(() => {
    clearInterval(timerId);
    console.log("Stopped");
    }, 5000);

 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