js代码实现倒计时
使用 setInterval 实现倒计时
通过 setInterval 定期更新剩余时间,适用于简单的倒计时需求。
function countdown(seconds, callback) {
const timer = setInterval(() => {
console.log(seconds);
seconds--;
if (seconds < 0) {
clearInterval(timer);
callback();
}
}, 1000);
}
// 示例:10秒倒计时
countdown(10, () => console.log('倒计时结束'));
使用 requestAnimationFrame 实现高精度倒计时
适用于需要高精度或动画效果的场景,避免 setInterval 的时间漂移问题。

function highPrecisionCountdown(duration, callback) {
const startTime = performance.now();
function update() {
const elapsed = performance.now() - startTime;
const remaining = Math.max(0, duration - Math.floor(elapsed / 1000));
console.log(remaining);
if (remaining > 0) {
requestAnimationFrame(update);
} else {
callback();
}
}
requestAnimationFrame(update);
}
// 示例:5秒高精度倒计时
highPrecisionCountdown(5, () => console.log('高精度倒计时结束'));
动态显示到目标时间的倒计时
计算当前时间到目标时间的差值,适合显示距离未来某个时间点的倒计时。

function targetCountdown(targetDate, updateCallback, endCallback) {
function tick() {
const now = new Date();
const diff = targetDate - now;
if (diff <= 0) {
endCallback();
return;
}
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const secs = Math.floor((diff % (1000 * 60)) / 1000);
updateCallback({ days, hours, mins, secs });
setTimeout(tick, 1000);
}
tick();
}
// 示例:显示到明天此时的倒计时
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
targetCountdown(
tomorrow,
({ days, hours, mins, secs }) => {
console.log(`${days}天 ${hours}时 ${mins}分 ${secs}秒`);
},
() => console.log('目标时间已到')
);
带暂停/继续功能的倒计时
通过封装计时器逻辑实现可控制的倒计时。
class PausableCountdown {
constructor(duration, callback) {
this.duration = duration;
this.callback = callback;
this.remaining = duration;
this.timer = null;
this.startTime = null;
}
start() {
this.startTime = Date.now();
this.timer = setInterval(() => {
this.remaining--;
console.log(this.remaining);
if (this.remaining <= 0) {
this.stop();
this.callback();
}
}, 1000);
}
pause() {
clearInterval(this.timer);
this.timer = null;
this.remaining -= Math.floor((Date.now() - this.startTime) / 1000);
}
stop() {
clearInterval(this.timer);
this.timer = null;
}
}
// 使用示例
const countdown = new PausableCountdown(10, () => console.log('完成'));
countdown.start();
// 暂停示例(通常在事件中调用)
// setTimeout(() => countdown.pause(), 3000);
使用 Web Worker 实现后台倒计时
避免主线程阻塞,适合需要长时间运行且精确的倒计时。
// worker.js
let timer;
self.onmessage = function(e) {
if (e.data.command === 'start') {
let seconds = e.data.seconds;
timer = setInterval(() => {
seconds--;
self.postMessage(seconds);
if (seconds <= 0) clearInterval(timer);
}, 1000);
} else if (e.data.command === 'stop') {
clearInterval(timer);
}
};
// 主线程代码
const worker = new Worker('worker.js');
worker.onmessage = (e) => {
console.log(e.data);
if (e.data <= 0) console.log('Worker倒计时结束');
};
// 启动15秒倒计时
worker.postMessage({ command: 'start', seconds: 15 });
// 停止示例
// worker.postMessage({ command: 'stop' });
每种方法适用于不同场景,可根据需求选择实现方式。简单场景推荐 setInterval,需要高精度时使用 requestAnimationFrame,复杂控制需求可选择类封装方案。






