js实现倒数

实现倒计时的 JavaScript 方法
使用 setInterval 实现基础倒计时
let count = 10; // 初始倒计时秒数
const timer = setInterval(() => {
console.log(count);
count--;
if (count < 0) {
clearInterval(timer);
console.log('倒计时结束');
}
}, 1000);
带日期计算的精确倒计时
const targetDate = new Date('2023-12-31T23:59:59').getTime();
const timer = setInterval(() => {
const now = new Date().getTime();
const distance = targetDate - now;
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
console.log(`${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`);
if (distance < 0) {
clearInterval(timer);
console.log('倒计时结束');
}
}, 1000);
使用 requestAnimationFrame 实现高性能倒计时
let startTime = Date.now();
const duration = 10000; // 10秒倒计时
function updateTimer() {
const elapsed = Date.now() - startTime;
const remaining = Math.max(0, duration - elapsed);
const seconds = Math.floor(remaining / 1000);
const milliseconds = remaining % 1000;
console.log(`${seconds}.${milliseconds.toString().padStart(3, '0')}`);
if (remaining > 0) {
requestAnimationFrame(updateTimer);
} else {
console.log('倒计时结束');
}
}
requestAnimationFrame(updateTimer);
带暂停和继续功能的倒计时
class Countdown {
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 = this.duration - (Date.now() - this.startTime);
if (this.remaining <= 0) {
this.stop();
this.callback();
}
}, 100);
}
pause() {
clearInterval(this.timer);
this.duration = this.remaining;
}
stop() {
clearInterval(this.timer);
}
}
// 使用示例
const countdown = new Countdown(10000, () => console.log('倒计时结束'));
countdown.start();
// countdown.pause(); // 暂停
// countdown.start(); // 继续
页面显示的倒计时实现
<div id="countdown">10</div>
<script>
let timeLeft = 10;
const countdownElement = document.getElementById('countdown');
const timer = setInterval(() => {
timeLeft--;
countdownElement.textContent = timeLeft;
if (timeLeft <= 0) {
clearInterval(timer);
countdownElement.textContent = '时间到!';
}
}, 1000);
</script>
这些方法覆盖了从简单到复杂的各种倒计时场景,可以根据具体需求选择适合的实现方式。对于需要高精度的场景,推荐使用 requestAnimationFrame 或带日期计算的实现;对于需要控制功能的场景,可以使用面向对象的实现方式。






