Spot the bug - #189: Button

A tiny web snippet with a quirky bug hiding inside.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Spot the Bug - quirky timer</title>
  <style>
    .box { width: 200px; height: 100px; background: #f0f0f0; border: 1px solid #ccc; display: flex; align-items: center; justify-content: center; }
  </style>
</head>
<body>
  <div class="box" id="box">0</div>
  <button id="start">Start</button>
  <script>
    // The goal: inner counter should update every second when started
    let count = 0;
    const box = document.getElementById('box');
    document.getElementById('start').addEventListener('click', function() {
      setInterval(function() {
        count++;
        box.textContent = count;
      }, 1000);
    });
  </script>
</body>
</html>

Reply with what is broken and how you would fix it.

The bug is the Start button doesn’t guard against being clicked more than once. Every click spins up a new setInterval, and nothing ever clears the old ones, so click it three times and the counter starts ticking three times a second instead of once.

Fix is to keep the interval id and bail out if one is already running:

let timer = null;
document.getElementById('start').addEventListener('click', function() {
  if (timer) return;
  timer = setInterval(function() {
    count++;
    box.textContent = count;
  }, 1000);
});

You could also disable the button once it starts, same idea — just don’t let a second click create a second timer.

Spot the Bug answer: setInterval is created on every click but never cleared, causing multiple timers and rapid increments after repeated starts

The fix:

store interval id and clear existing one before starting a new interval: let intervalId; document.getElementById('start').addEventListener('click', function() { if (intervalId) clearInterval(intervalId); intervalId = setInterval(function() { count++; box.textContent = count; }, 1000); });

Why:
Clicking Start multiple times would create multiple intervals, all updating the counter independently, leading to faster and unexpected increments. Clearing the previous interval before starting a new one ensures only a single timer runs.


Nobody got this one. It was a sneaky one.

Close but not quite:

@PipMuse - They identify the issue (multiple intervals) but only partially propose a fix; they suggest guarding but the snippet ends incomplete and misses clearing/storing the interval id properly for reuse.

First-answer leaderboard

  1. @emmawalter5 - 15 (firsts) :trophy:
  2. @Apexcodes - 9 (firsts)
  3. @kirupa - 8 (firsts)
  4. @PipMuse - 5 (firsts)
  5. @adnanahmed - 2 (firsts)

Bonus round: challenge: Modify the code so that pressing a new “Start” while the timer is running also pauses the timer (a separate Pause button), and add a “Reset” button that stops the timer and resets the counter to zero.