js实现自定义倒计时器
实现自定义倒计时器
以下是一个基于JavaScript的自定义倒计时器实现方案,支持灵活配置和功能扩展。

基本倒计时功能实现
class CountdownTimer {
constructor(endTime, updateCallback, finishCallback) {
this.endTime = new Date(endTime).getTime();
this.updateCallback = updateCallback;
this.finishCallback = finishCallback;
this.timer = null;
}
start() {
this.timer = setInterval(() => {
const now = new Date().getTime();
const distance = this.endTime - now;
if (distance <= 0) {
this.stop();
if (this.finishCallback) this.finishCallback();
return;
}
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);
if (this.updateCallback) {
this.updateCallback({ days, hours, minutes, seconds });
}
}, 1000);
}
stop() {
clearInterval(this.timer);
}
}
使用示例
// 创建倒计时实例
const timer = new CountdownTimer(
'2024-12-31T23:59:59',
(time) => {
console.log(`${time.days}天 ${time.hours}小时 ${time.minutes}分 ${time.seconds}秒`);
},
() => {
console.log('倒计时结束!');
}
);
// 启动倒计时
timer.start();
// 如需停止
// timer.stop();
高级功能扩展
格式化输出支持

class CountdownTimer {
// ...原有代码...
formatTime({ days, hours, minutes, seconds }) {
return `${this.padZero(days)}:${this.padZero(hours)}:${this.padZero(minutes)}:${this.padZero(seconds)}`;
}
padZero(num) {
return num < 10 ? `0${num}` : num;
}
}
暂停/继续功能
class CountdownTimer {
constructor(endTime, updateCallback, finishCallback) {
// ...原有代码...
this.remainingTime = 0;
this.isPaused = false;
}
pause() {
if (!this.isPaused) {
clearInterval(this.timer);
this.remainingTime = this.endTime - new Date().getTime();
this.isPaused = true;
}
}
resume() {
if (this.isPaused) {
this.endTime = new Date().getTime() + this.remainingTime;
this.start();
this.isPaused = false;
}
}
}
页面显示示例
<div id="countdown"></div>
<script>
const display = document.getElementById('countdown');
const timer = new CountdownTimer(
'2024-12-31T23:59:59',
(time) => {
display.textContent = timer.formatTime(time);
},
() => {
display.textContent = '活动已结束!';
}
);
timer.start();
</script>
注意事项
- 确保传入的结束时间是有效的Date可解析格式
- 考虑时区问题,建议使用ISO格式日期字符串
- 在组件卸载或页面离开时调用stop()方法清除定时器
- 对于长时间倒计时,可考虑使用Web Worker避免主线程阻塞
这个实现提供了基本倒计时功能,并可通过扩展方法增加更多自定义功能,如不同时间单位显示、多语言支持、样式定制等。






