秒杀 js 实现
秒杀功能的实现要点
前端实现秒杀功能需要处理高并发、时间同步、防刷等问题。以下是基于JavaScript的核心实现逻辑:
倒计时功能
使用定时器实现秒杀倒计时,需确保与服务器时间同步:

function countDown(endTime) {
const timer = setInterval(() => {
const now = new Date().getTime();
const distance = endTime - 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);
if (distance < 0) {
clearInterval(timer);
document.getElementById("countdown").innerHTML = "秒杀已开始";
}
}, 1000);
}
按钮状态控制
秒杀未开始时禁用按钮:
const seckillBtn = document.getElementById('seckill-btn');
if (new Date() < startTime) {
seckillBtn.disabled = true;
seckillBtn.innerText = '秒杀未开始';
}
请求并发控制
使用Promise和限流策略:

let requestQueue = [];
let isRequesting = false;
async function throttleRequest() {
if (isRequesting) {
return Promise.reject('请求过于频繁');
}
isRequesting = true;
try {
const res = await fetch('/seckill', {method: 'POST'});
return res.json();
} finally {
isRequesting = false;
if (requestQueue.length > 0) {
throttleRequest();
}
}
}
防止重复提交
提交后立即禁用按钮:
seckillBtn.addEventListener('click', () => {
seckillBtn.disabled = true;
throttleRequest()
.then(data => {
alert(data.message);
})
.catch(err => {
seckillBtn.disabled = false;
console.error(err);
});
});
时间同步方案
定期与服务器同步时间:
function syncServerTime() {
fetch('/api/time')
.then(res => res.json())
.then(data => {
const serverTime = new Date(data.time);
const localTime = new Date();
timeDiff = serverTime - localTime;
});
}
// 每5分钟同步一次
setInterval(syncServerTime, 300000);
性能优化建议
- 使用WebWorker处理倒计时计算
- 采用本地缓存记录已售罄状态
- 实现请求队列避免瞬间高并发
- 添加动画效果提升用户体验
后端需要配合实现库存原子性操作、分布式锁等机制,前端主要关注用户体验和请求控制。实际项目中建议使用WebSocket实现状态实时推送。






