js实现倒计时秒
使用 setInterval 实现倒计时秒
通过 setInterval 定时器每秒更新倒计时显示,适用于简单的倒计时需求。

function countdown(seconds, callback) {
const timer = setInterval(() => {
console.log(seconds);
seconds--;
if (seconds < 0) {
clearInterval(timer);
callback && callback();
}
}, 1000);
}
// 示例:10秒倒计时结束后打印提示
countdown(10, () => console.log('倒计时结束'));
使用 requestAnimationFrame 实现高精度倒计时
通过 requestAnimationFrame 实现更平滑的倒计时,避免 setInterval 的误差积累问题。

function countdown(seconds, callback) {
const startTime = Date.now();
const endTime = startTime + seconds * 1000;
function update() {
const remaining = Math.max(0, Math.ceil((endTime - Date.now()) / 1000));
console.log(remaining);
if (remaining > 0) {
requestAnimationFrame(update);
} else {
callback && callback();
}
}
update();
}
// 示例:5秒倒计时
countdown(5, () => console.log('时间到'));
带暂停/继续功能的倒计时
通过状态管理实现可暂停的倒计时功能。
class Countdown {
constructor(seconds, callback) {
this.remaining = seconds;
this.callback = callback;
this.timer = null;
}
start() {
this.timer = setInterval(() => {
console.log(this.remaining);
this.remaining--;
if (this.remaining < 0) {
this.stop();
this.callback && 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(); // 可随时暂停
页面显示的DOM倒计时
实现将倒计时显示在HTML页面上的完整示例。
<div id="countdown">10</div>
<button id="startBtn">开始</button>
<button id="pauseBtn">暂停</button>
<script>
let timer;
let seconds = 10;
const display = document.getElementById('countdown');
document.getElementById('startBtn').addEventListener('click', () => {
clearInterval(timer);
timer = setInterval(() => {
display.textContent = seconds--;
if (seconds < 0) {
clearInterval(timer);
display.textContent = '时间到';
}
}, 1000);
});
document.getElementById('pauseBtn').addEventListener('click', () => {
clearInterval(timer);
});
</script>
注意事项
setInterval可能因主线程阻塞导致时间不准确,重要场景建议使用服务器时间或Web Worker- 移动端页面切到后台时定时器可能被暂停,需要监听
visibilitychange事件 - 长时间倒计时需考虑内存泄漏问题,及时清除定时器
- 样式优化可添加过渡动画增强用户体验






