🇯🇵 日本語 | 🇺🇸 English | 🇪🇸 Español | 🇵🇹 Português | 🇹🇭 ไทย | 🇨🇳 中文

How to Use JavaScript setInterval [Beginner Friendly]

A handy function for executing repeated tasks

🔁 What is setInterval?

setInterval() is a function that repeatedly executes another function at specified intervals.

setInterval(function, intervalInMilliseconds);
    
  

🕒 Example: Display current time every second


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Real-time Clock</title>
  <style>
    body {
      font-family: sans-serif;
      text-align: center;
      padding: 50px;
      background: #f9f9f9;
    }
    h1 {
      font-size: 2rem;
      margin-bottom: 1rem;
    }
    #clock {
      font-size: 2.5rem;
      font-weight: bold;
      color: #333;
    }
  </style>
</head>
<body>

  <h1>🕒 Current Time</h1>
  <div id="clock">--:--:--</div>

  <!-- Script -->
  <script>
    setInterval(() => {
      const now = new Date();
      const time = now.toLocaleTimeString();
      document.getElementById("clock").textContent = time;
    }, 1000);
  </script>

</body>
</html>
    
👇This will appear👇
--:--:--

🧩 Advanced Techniques and Precautions for setInterval

setInterval() is a very convenient function, but if not used properly, it can cause performance issues or unexpected behavior. This section introduces practical use cases and important points to watch out for.

🎯 Effective Use Cases

setInterval() is useful in scenarios such as UI updates and animation loops. Common examples include displaying a digital clock in real time, running a countdown timer, or showing periodic notifications.

⚠ Be Careful of Infinite Loops

When using setInterval(), be sure to implement a proper stop mechanism. For example, if you forget to call clearInterval() under certain conditions, the interval will continue running even if the user leaves the page, potentially consuming memory unnecessarily.

🧪 Difference from setTimeout

While setTimeout() executes a function only once, setInterval() repeatedly runs the function at set intervals. Choosing the right one depends on the use case.

As shown, setInterval() is easy to use for beginners, but it’s important to apply it appropriately based on the situation.