倒计时计时器是一种常见的功能,用于显示从当前时间到某个特定时间的剩余时间。在前端开发中,通常使用JavaScript来实现这一功能。
以下是一个简单的JavaScript倒计时计时器的实现示例:
function startCountdown(endTime) {
const interval = setInterval(() => {
const now = new Date().getTime();
const distance = endTime - now;
if (distance < 0) {
clearInterval(interval);
document.getElementById('countdown').innerHTML = "EXPIRED";
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);
document.getElementById('countdown').innerHTML = `${days}d ${hours}h ${minutes}m ${seconds}s`;
}, 1000);
}
// 设置结束时间为当前时间后的1小时
const endTime = new Date().getTime() + 3600000;
startCountdown(endTime);
setInterval
函数存在一定的延迟。setTimeout
递归调用来提高准确性。localStorage
或通过服务器端传递,以便在页面加载时恢复状态。function startCountdown(endTime) {
function updateCountdown() {
const now = new Date().getTime();
const distance = endTime - now;
if (distance < 0) {
clearInterval(interval);
document.getElementById('countdown').innerHTML = "EXPIRED";
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);
document.getElementById('countdown').innerHTML = `${days}d ${hours}h ${minutes}m ${seconds}s`;
setTimeout(updateCountdown, 1000);
}
updateCountdown();
}
// 设置结束时间为当前时间后的1小时
const endTime = new Date().getTime() + 3600000;
startCountdown(endTime);
通过这种方式,可以确保倒计时计时器更加准确和可靠。
领取专属 10元无门槛券
手把手带您无忧上云