js倒计时
根据实际经过的时间动态调整下一次更新的时间,从而减少延迟问题
const countdown = (endTime: any, onUpdate: any, onEnd: any) => {
const updateInterval = 1000; // 更新间隔(毫秒)
let lastUpdateTime = new Date().getTime();
const update = () => {
const currentTime = new Date().getTime();
const remainingTime = Math.max(endTime - currentTime, 0);
const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
const minutes = Math.floor(
(remainingTime % (1000 * 60 * 60)) / (1000 * 60),
);
const hours = Math.floor(
(remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60),
);
const days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
onUpdate({ days, hours, minutes, seconds });
if (remainingTime <= 0) {
clearInterval(intervalId);
onEnd();
} else {
const elapsedTime = currentTime - lastUpdateTime;
const nextUpdateInterval =
updateInterval - (elapsedTime % updateInterval);
setTimeout(update, nextUpdateInterval);
lastUpdateTime = currentTime;
}
};
const intervalId = setTimeout(update, updateInterval);
};
const endTime = new Date().getTime() + 1000 * 60 * 60 * 24;
countdown(
endTime,
({ days, hours, minutes, seconds }:any) => {
console.log(`倒计时:${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`);
},
() => {
console.log('倒计时结束');
}
);