用js实现一个倒计时器
实现基础倒计时器
创建一个简单的倒计时器需要设置目标时间,计算剩余时间并更新显示。以下代码展示如何实现从10秒开始的倒计时:
let countdown = 10;
const timerElement = document.getElementById('timer');
function updateTimer() {
timerElement.textContent = countdown;
if (countdown <= 0) {
clearInterval(interval);
timerElement.textContent = '时间到!';
return;
}
countdown--;
}
const interval = setInterval(updateTimer, 1000);
自定义时长倒计时
允许用户输入自定义倒计时时长:
function startCustomCountdown() {
const minutes = parseInt(document.getElementById('minutes').value) || 0;
const seconds = parseInt(document.getElementById('seconds').value) || 0;
let totalSeconds = minutes * 60 + seconds;
const interval = setInterval(() => {
const mins = Math.floor(totalSeconds / 60);
const secs = totalSeconds % 60;
document.getElementById('custom-timer').textContent =
`${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
if (totalSeconds <= 0) clearInterval(interval);
totalSeconds--;
}, 1000);
}
带暂停/继续功能的倒计时
实现可控制的倒计时器:
let timer;
let remainingTime = 300; // 5分钟
let isRunning = false;
function toggleTimer() {
if (isRunning) {
clearInterval(timer);
isRunning = false;
} else {
timer = setInterval(updateDisplay, 1000);
isRunning = true;
}
}
function updateDisplay() {
const minutes = Math.floor(remainingTime / 60);
const seconds = remainingTime % 60;
document.getElementById('control-timer').textContent =
`${minutes}:${seconds.toString().padStart(2, '0')}`;
if (remainingTime <= 0) {
clearInterval(timer);
return;
}
remainingTime--;
}
精确到毫秒的倒计时
使用requestAnimationFrame实现高精度倒计时:
let startTime;
let duration = 5000; // 5秒
function startPreciseCountdown() {
startTime = performance.now();
requestAnimationFrame(updatePreciseTimer);
}
function updatePreciseTimer(timestamp) {
const elapsed = timestamp - startTime;
const remaining = Math.max(0, duration - elapsed);
const seconds = (remaining / 1000).toFixed(2);
document.getElementById('precise-timer').textContent = seconds;
if (remaining > 0) {
requestAnimationFrame(updatePreciseTimer);
}
}
页面不可见时暂停倒计时
使用Page Visibility API优化性能:

document.addEventListener('visibilitychange', () => {
if (document.hidden) {
clearInterval(timer);
} else {
timer = setInterval(updateTimer, 1000);
}
});
每个实现方案都针对不同使用场景,基础版本适合简单需求,自定义时长版本提供灵活性,控制版本适合需要交互的场景,高精度版本适用于对时间敏感的应用。根据实际需求选择合适的实现方式。






