You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:实现带10秒加时按钮的JavaScript倒计时器

实现带10秒加时按钮的JavaScript倒计时器

完整代码实现

HTML结构

<div class="timer-container">
  <div id="countdown">60</div>
  <button id="add-time-btn">+10秒</button>
</div>

CSS样式(贴近需求效果)

.timer-container {
  text-align: center;
  margin-top: 50px;
}

#countdown {
  font-size: 80px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

#add-time-btn {
  padding: 10px 20px;
  font-size: 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

#add-time-btn:hover {
  background-color: #45a049;
}

#add-time-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

JavaScript核心逻辑

let remainingTime = 60; // 可自行修改初始倒计时时长
let timerInterval = null;

const countdownEl = document.getElementById('countdown');
const addTimeBtn = document.getElementById('add-time-btn');

// 启动/重启倒计时
function startCountdown() {
  // 清除已有定时器,避免多实例冲突
  if (timerInterval) clearInterval(timerInterval);
  
  timerInterval = setInterval(() => {
    remainingTime--;
    countdownEl.textContent = remainingTime;
    
    if (remainingTime <= 0) {
      clearInterval(timerInterval);
      timerInterval = null;
      countdownEl.textContent = '时间到!';
      addTimeBtn.disabled = true;
    }
  }, 1000);
}

// 加时按钮点击事件
addTimeBtn.addEventListener('click', () => {
  remainingTime += 10;
  countdownEl.textContent = remainingTime;
  
  // 若倒计时已停止,重新启动并启用按钮
  if (!timerInterval) {
    addTimeBtn.disabled = false;
    startCountdown();
  }
});

// 页面加载完成后启动初始倒计时
window.addEventListener('load', startCountdown);

关键逻辑说明

  • 定时器防重复:每次启动倒计时前清除旧定时器,避免多个定时器同时运行导致时间跳变
  • 加时处理:点击按钮直接累加10秒并更新显示,若倒计时已结束则自动重启
  • 边界控制:时间归0时停止定时器、禁用加时按钮,显示明确提示

内容的提问来源于stack exchange,提问作者5C6 purushotham Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:31:02