⏳ 倒计时定时器(10 秒)
使用 JavaScript 的 setInterval 创建从 10 秒开始的倒计时。
到 0 时显示 “✅ 时间到!”
- 🎬 测验/测试:显示时间限制
- 🍜 烹饪网站:倒计时显示煮食时间
- 📊 演示计时器:用于时间管理的简易工具
- 🎮 游戏限时:也适用于自制迷你游戏!
🧪 试试看:点击 “开始” 后开始 10 秒倒计时。
到 0 秒时显示 ✅ “时间到!”
点击 “重置” 可随时重新开始!
👇就是这个👇
剩余时间:10 秒
<!DOCTYPE html>
<html lang="zh">
<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秒”开始倒计时,可以先将其换算为总秒数,并按如下方式转换显示:
let totalSeconds = 90;
setInterval(() => {
totalSeconds--;
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
document.getElementById("countdown").textContent =
"剩余时间:" + minutes + " 分 " + seconds + " 秒";
}, 1000);
- 📏 可自由设定倒计时时长(如 5 分钟、90 秒 等)
- 📱 易于与表单或用户输入搭配使用
- 🧠 “分钟:秒”格式更直观易懂
实现倒计时的核心思想是将“时间逻辑”与“显示逻辑”分开
理解这一点后,你可以进一步扩展功能,例如暂停、继续、进度条显示等。