⏱ setInterval + clearInterval の使い方

JavaScriptで一定時間ごとに繰り返し処理を行いたいときに使う基本的な構文です。
例えば以下のような場面で活用されます:

  • 🕒 デジタル時計setIntervalで1秒ごとに現在時刻を更新

  • 🖼 画像スライドショー:5秒ごとに写真を切り替える

  • 📢 自動通知:定期的にアラートやメッセージを表示

  • 🧮 カウントアップやカウントダウン:数値を定期的に更新

  • 🎮 アニメーションやゲーム:一定時間ごとに動きを更新

カウント: 0
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>カウントアップ(1秒ごと)</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>⏱ カウントアップ(1秒ごと)</h1>
  <div id="counter">カウント: 0</div>

  <button onclick="startCounting()">スタート</button>
  <button onclick="stopCounting()">ストップ</button>

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

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

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

</body>
</html>

🧩 setIntervalを使った「交互切り替え処理」

setInterval は、カウントアップやタイマーだけでなく、「状態を交互に切り替える処理」にも使える便利な関数です。

たとえば、以下のような場面で活躍します:

  • 💡 テキストを チカチカ点滅 させて注意喚起したいとき
  • 🔁 ボタンのラベルを ON / OFF で交互に変えたいとき
  • 🎨 背景色を数秒ごとに切り替えて 視覚的演出 を加えたいとき

以下は、3秒ごとに背景色を交互に変更する例です:

<script>
let isBlue = true;

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

このように、setInterval は「記憶 → 反転 → 再代入」というシンプルな流れで、動きのあるUI を実装できます。

また、clearInterval() を使えば処理の停止も可能です。今後は「点滅ボタン」や「切り替え停止ボタン」の活用例も紹介予定です。