⏳ カウントダウンタイマー(10秒)

JavaScriptのsetIntervalを使って,10秒からのカウントダウンを作ります。
0になったら「時間切れ」を表示!

  • 🎬 クイズ・テスト:制限時間を表示
  • 🍜 料理サイト:ゆで時間のカウントダウン
  • 📊 プレゼンタイマー:時間管理用の簡易ツール
  • 🎮 ゲームの制限時間:自作ミニゲーム用にも!

🧪 試してみるとこんな動き:「スタート」押すと10秒カウントダウン開始
0秒で ✅ 時間切れです! を表示
「リセット」で何度でもやり直せる!

👇これね👇
残り時間: 10 秒
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>カウントダウンタイマー</title>
  <style>
    body {
      font-family: sans-serif;
      text-align: center;
      padding: 50px;
    }
    #countdown {
      font-size: 2rem;
      margin: 20px 0;
    }
    button {
      font-size: 1rem;
      padding: 10px 20px;
      margin: 5px;
      cursor: pointer;
    }
  </style>
</head>
<body>

  <h1>⏳ カウントダウンタイマー</h1>
  <div id="countdown">残り時間: 10 秒</div>
  <button onclick="startCountdown()">スタート</button>
  <button onclick="resetCountdown()">リセット</button>

  <script>
    let timeLeft = 10;
    let timerId = null;

    function startCountdown() {
      if (timerId !== null) return;
      document.getElementById("countdown").textContent = "残り時間: " + timeLeft + " 秒";

      timerId = setInterval(() => {
        timeLeft--;
        if (timeLeft > 0) {
          document.getElementById("countdown").textContent = "残り時間: " + timeLeft + " 秒";
        } else {
          clearInterval(timerId);
          timerId = null;
          document.getElementById("countdown").textContent = "✅ 時間切れです!";
        }
      }, 1000);
    }

    function resetCountdown() {
      clearInterval(timerId);
      timerId = null;
      timeLeft = 10;
      document.getElementById("countdown").textContent = "残り時間: 10 秒";
    }
  </script>

</body>
</html>
  

⏱ 分単位のカウントダウンにも対応しよう

このテンプレートは「10秒」固定のタイマーですが、少し工夫すれば分・秒の形式にも対応できます。

例えば「1分30秒」などの設定をしたい場合は、以下のように合計秒数で内部管理し、Math.floor()%(剰余演算子)で分と秒を分けて表示する方法が便利です。

let totalSeconds = 90;

setInterval(() => {
  totalSeconds--;
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  document.getElementById("countdown").textContent =
    "残り時間: " + minutes + "分 " + seconds + "秒";
}, 1000);
  • 📏 任意の時間(例:5分・90秒など)を簡単に設定可能
  • 📱 フォーム入力で時間を受け取る実装にも対応しやすい
  • 🧠 「分:秒」形式のほうがユーザーにとってわかりやすい

タイマーの応用力を広げる鍵は、時間の扱いを「見た目」と「内部値」に分けて考えることです。
数字の制御に慣れてくると、さらに高度なタイマー(一時停止・再開・残り時間バーなど)も作れるようになります!