js实现倒数
实现倒计时的 JavaScript 方法
使用 setInterval 实现基础倒计时
以下代码展示如何实现一个从指定时间开始的倒计时功能:

let countdownTime = 10; // 倒数秒数
const timer = setInterval(() => {
console.log(countdownTime);
countdownTime--;
if (countdownTime < 0) {
clearInterval(timer);
console.log('倒计时结束');
}
}, 1000);
带日期显示的完整倒计时
这段代码可以计算距离某个未来日期的剩余时间:

function startCountdown(targetDate) {
const countdown = setInterval(() => {
const now = new Date();
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(countdown);
console.log('倒计时结束');
}
}, 1000);
}
// 使用示例:设置未来某个日期
const targetDate = new Date('2024-12-31T23:59:59');
startCountdown(targetDate);
页面显示的倒计时实现
这段代码将倒计时显示在HTML页面上:
function displayCountdown(seconds, elementId) {
const display = document.getElementById(elementId);
let remaining = seconds;
const timer = setInterval(() => {
display.textContent = remaining;
remaining--;
if (remaining < 0) {
clearInterval(timer);
display.textContent = '时间到!';
}
}, 1000);
}
// HTML中需要有一个元素:<div id="countdown"></div>
displayCountdown(60, 'countdown');
带暂停和继续功能的倒计时
这段代码实现了可以暂停和继续的倒计时:
class Countdown {
constructor(duration, updateCallback, finishCallback) {
this.duration = duration;
this.updateCallback = updateCallback;
this.finishCallback = finishCallback;
this.remaining = duration;
this.timer = null;
}
start() {
this.timer = setInterval(() => {
this.updateCallback(this.remaining);
this.remaining--;
if (this.remaining < 0) {
this.stop();
this.finishCallback();
}
}, 1000);
}
pause() {
clearInterval(this.timer);
}
stop() {
clearInterval(this.timer);
this.remaining = this.duration;
}
}
// 使用示例
const countdown = new Countdown(
10,
(time) => console.log(time),
() => console.log('倒计时结束')
);
countdown.start();
这些方法提供了从简单到复杂的倒计时实现方案,可以根据具体需求选择合适的实现方式。






