js代码实现倒计时
使用 setInterval 实现倒计时
通过 setInterval 定时器每秒更新显示剩余时间,适用于简单的倒计时场景。
function countdown(seconds, callback) {
const timer = setInterval(() => {
seconds--;
console.log(seconds);
if (seconds <= 0) {
clearInterval(timer);
callback?.();
}
}, 1000);
}
// 使用示例
countdown(10, () => console.log('倒计时结束'));
使用 setTimeout 递归实现
递归调用 setTimeout 实现更精确的倒计时控制,避免 setInterval 的误差累积问题。
function recursiveCountdown(seconds, callback) {
console.log(seconds);
if (seconds > 0) {
setTimeout(() => recursiveCountdown(seconds - 1, callback), 1000);
} else {
callback?.();
}
}
// 使用示例
recursiveCountdown(5, () => console.log('时间到'));
带暂停/继续功能的倒计时
通过封装倒计时逻辑实现可控制的倒计时器,支持暂停和继续功能。
class Countdown {
constructor(seconds, callback) {
this.seconds = seconds;
this.callback = callback;
this.timer = null;
}
start() {
this.timer = setInterval(() => {
this.seconds--;
console.log(this.seconds);
if (this.seconds <= 0) {
this.stop();
this.callback?.();
}
}, 1000);
}
pause() {
clearInterval(this.timer);
}
stop() {
clearInterval(this.timer);
this.timer = null;
}
}
// 使用示例
const cd = new Countdown(3, () => console.log('完成'));
cd.start();
// cd.pause(); // 暂停
// cd.start(); // 继续
精确到毫秒的倒计时
使用 performance.now() 实现高精度倒计时,适用于需要精确计时的场景。
function preciseCountdown(duration, updateCallback, endCallback) {
const startTime = performance.now();
let requestId;
function update() {
const elapsed = performance.now() - startTime;
const remaining = Math.max(0, duration - elapsed);
updateCallback?.(remaining);
if (remaining > 0) {
requestId = requestAnimationFrame(update);
} else {
endCallback?.();
}
}
requestId = requestAnimationFrame(update);
return {
stop: () => cancelAnimationFrame(requestId)
};
}
// 使用示例
const counter = preciseCountdown(
5000,
(ms) => console.log((ms/1000).toFixed(2)),
() => console.log('精确倒计时结束')
);
// counter.stop(); // 可随时停止
页面显示的倒计时组件
实现一个在网页上显示的完整倒计时组件,包含 HTML 结构和样式控制。
<div id="countdown-display">00:00:00</div>
<button id="start-btn">开始</button>
<button id="pause-btn">暂停</button>
<script>
class DisplayCountdown {
constructor(displayElement, initialSeconds) {
this.display = displayElement;
this.seconds = initialSeconds;
this.timer = null;
this.updateDisplay();
}
start() {
if (!this.timer && this.seconds > 0) {
this.timer = setInterval(() => {
this.seconds--;
this.updateDisplay();
if (this.seconds <= 0) this.stop();
}, 1000);
}
}
pause() {
clearInterval(this.timer);
this.timer = null;
}
stop() {
this.pause();
this.seconds = 0;
this.updateDisplay();
}
updateDisplay() {
const hours = Math.floor(this.seconds / 3600);
const mins = Math.floor((this.seconds % 3600) / 60);
const secs = this.seconds % 60;
this.display.textContent =
`${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
}
// 使用示例
const display = new DisplayCountdown(document.getElementById('countdown-display'), 30);
document.getElementById('start-btn').addEventListener('click', () => display.start());
document.getElementById('pause-btn').addEventListener('click', () => display.pause());
</script>
时区敏感的倒计时
处理跨时区倒计时需求,确保在不同时区显示正确的剩余时间。
function timezoneCountdown(targetDate, updateCallback) {
function update() {
const now = new Date();
const diff = targetDate - now;
if (diff <= 0) {
updateCallback?.(0);
return;
}
const seconds = Math.floor(diff / 1000);
updateCallback?.(seconds);
setTimeout(update, 1000);
}
update();
}
// 使用示例:计算到2023年12月31日的倒计时
const newYear = new Date('2023-12-31T23:59:59Z');
timezoneCountdown(newYear, (sec) => {
const days = Math.floor(sec / 86400);
const hours = Math.floor((sec % 86400) / 3600);
console.log(`${days}天${hours}小时`);
});






