在JavaScript中实现秒杀活动的倒计时功能,通常会涉及到以下几个基础概念:
setInterval
定时刷新剩余时间。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>秒杀倒计时</title>
</head>
<body>
<div id="countdown">加载中...</div>
<script>
// 假设秒杀结束时间是2023年12月31日23:59:59
const endTime = new Date('2023-12-31T23:59:59').getTime();
function updateCountdown() {
const now = new Date().getTime();
const distance = endTime - now;
if (distance < 0) {
clearInterval(interval);
document.getElementById('countdown').innerHTML = "秒杀结束";
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 + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒 ";
}
// 每秒更新一次
const interval = setInterval(updateCountdown, 1000);
updateCountdown(); // 初始化显示
</script>
</body>
</html>
localStorage
或sessionStorage
中来保持倒计时状态。// 从服务器获取当前时间
fetch('/api/current-time')
.then(response => response.json())
.then(data => {
const serverTime = new Date(data.currentTime).getTime();
const endTime = new Date(data.endTime).getTime();
// 继续使用上面的updateCountdown函数
});
通过以上方法,可以实现一个稳定且高效的秒杀活动倒计时功能。
领取专属 10元无门槛券
手把手带您无忧上云