js 实现倒计时
使用 setInterval 实现倒计时
通过 setInterval 定期更新倒计时显示,适用于简单的倒计时场景。
function countdown(seconds, elementId) {
const element = document.getElementById(elementId);
const timer = setInterval(() => {
element.textContent = seconds;
seconds--;
if (seconds < 0) {
clearInterval(timer);
element.textContent = '时间到!';
}
}, 1000);
}
// 调用示例
countdown(10, 'countdown-display');
使用 requestAnimationFrame 实现高精度倒计时
适用于需要高精度计时的场景,如动画或游戏。

function highPrecisionCountdown(duration, elementId) {
const element = document.getElementById(elementId);
const startTime = performance.now();
function updateTimer(currentTime) {
const elapsed = currentTime - startTime;
const remaining = Math.max(0, duration - Math.floor(elapsed / 1000));
element.textContent = remaining;
if (remaining > 0) {
requestAnimationFrame(updateTimer);
} else {
element.textContent = '时间到!';
}
}
requestAnimationFrame(updateTimer);
}
// 调用示例
highPrecisionCountdown(10, 'countdown-display');
使用 Date 对象实现跨天倒计时
适用于需要显示天、小时、分钟和秒的长时间倒计时。

function daysCountdown(endTime, elementId) {
const element = document.getElementById(elementId);
function update() {
const now = new Date();
const diff = endTime - now;
if (diff <= 0) {
element.textContent = '时间到!';
return;
}
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
element.textContent = `${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`;
setTimeout(update, 1000);
}
update();
}
// 调用示例
const endDate = new Date();
endDate.setDate(endDate.getDate() + 2); // 2天后
daysCountdown(endDate, 'countdown-display');
使用 Web Worker 实现后台倒计时
适用于需要后台运行的倒计时,即使页面不活跃也能继续计时。
// main.js
function startWorkerCountdown(seconds, elementId) {
const element = document.getElementById(elementId);
const worker = new Worker('countdown-worker.js');
worker.postMessage(seconds);
worker.onmessage = function(e) {
if (e.data === 'done') {
element.textContent = '时间到!';
worker.terminate();
} else {
element.textContent = e.data;
}
};
}
// countdown-worker.js
self.onmessage = function(e) {
let seconds = e.data;
const timer = setInterval(() => {
self.postMessage(seconds);
seconds--;
if (seconds < 0) {
clearInterval(timer);
self.postMessage('done');
}
}, 1000);
};
使用 Promise 和 async/await 实现倒计时
适用于需要与其他异步操作配合的倒计时场景。
async function asyncCountdown(seconds, elementId) {
const element = document.getElementById(elementId);
for (let i = seconds; i >= 0; i--) {
element.textContent = i;
await new Promise(resolve => setTimeout(resolve, 1000));
}
element.textContent = '时间到!';
}
// 调用示例
asyncCountdown(10, 'countdown-display');
注意事项
- 性能考虑:
setInterval在页面不活跃时可能会延迟,requestAnimationFrame或 Web Worker 更适合精确计时 - 内存泄漏:使用
setInterval或setTimeout时要记得清除定时器 - 跨标签页同步:如需多个标签页同步倒计时,可使用
BroadcastChannel或localStorage事件 - 时区问题:使用
Date对象时要注意客户端时区差异






