⏱ How to use setInterval + clearInterval

This is the basic syntax used in JavaScript when you want to execute tasks repeatedly at regular intervals.
For example, it's used in the following scenarios:

  • 🕒 Digital clock: Updates the current time every second using setInterval

  • 🖼 Image slideshow: Changes photos every 5 seconds

  • 📢 Auto notifications: Displays alerts or messages periodically

  • 🧮 Counting up or down: Regularly updates numbers

  • 🎮 Animations or games: Updates movements at regular intervals

Count: 0
  
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Counter (increments every second)</title>
  <style>
    body {
      font-family: sans-serif;
      text-align: center;
      padding: 2rem;
    }
    #counter {
      font-size: 2rem;
      margin: 1rem 0;
    }
    button {
      font-size: 1rem;
      padding: 0.5rem 1.2rem;
      margin: 0.5rem;
    }
  </style>
</head>
<body>

  <h1>⏱ Counter (increments every second)</h1>
  <div id="counter">Count: 0</div>

  <button onclick="startCounting()">Start</button>
  <button onclick="stopCounting()">Stop</button>

  <script>
    let count = 0;
    let intervalId = null;

    function startCounting() {
      if (intervalId !== null) return;
      intervalId = setInterval(() => {
        count++;
        document.getElementById("counter").textContent = "Count: " + count;
      }, 1000);
    }

    function stopCounting() {
      clearInterval(intervalId);
      intervalId = null;
    }
  </script>

</body>
</html>

🧩 Using setInterval for "Alternating Toggle Effects"

The setInterval function is not just for counters or timers—it can also be used to repeatedly toggle states.

For example, it’s useful in the following scenarios:

  • 💡 Making text blink to attract attention
  • 🔁 Switching a button label between ON / OFF
  • 🎨 Changing the background color every few seconds for a visual effect

Here's an example that alternates the background color every 3 seconds:

<script>
let isBlue = true;

setInterval(() => {
  document.body.style.backgroundColor = isBlue ? "#cceeff" : "#ffeedd";
  isBlue = !isBlue;
}, 3000);
</script>

As shown, setInterval lets you build dynamic UI with a simple flow of "remember → toggle → reassign."

You can also use clearInterval() to stop the toggling process. Future examples may include blinking buttons or toggle-stop controls.