# 现在实现倒计时都这么卷了吗？

「这是我参与11月更文挑战的第3天，活动详情查看：2021最后一次更文挑战

``````const totalDuration = 10 * 1000;
let requestRef = null;
let startTime;
let prevEndTime;
let prevTime;
let currentCount = totalDuration;
let endTime;
let timeDifferance = 0; // 每1s倒计时偏差值，单位ms
let interval = 1000;
let nextTime = interval;

setInterval(() => {
let n = 0;
while (n++ < 1000000000);
}, 0);

const animate = (timestamp) => {
if (prevTime !== undefined) {
const deltaTime = timestamp - prevTime;
if (deltaTime >= nextTime) {
prevTime = timestamp;
prevEndTime = endTime;
endTime = new Date().getTime();
currentCount = currentCount - 1000;
console.log("currentCount: ", currentCount / 1000);
timeDifferance = endTime - startTime - (totalDuration - currentCount);
console.log(timeDifferance);
nextTime = interval - timeDifferance;
// 慢太多了，就立刻执行下一个循环
if (nextTime < 0) {
nextTime = 0;
}
console.log(`执行下一次渲染的时间是：\${nextTime}ms`);
if (currentCount <= 0) {
currentCount = 0;
cancelAnimationFrame(requestRef);
console.log(`累计偏差值： \${endTime - startTime - totalDuration}ms`);
return;
}
}
} else {
startTime = new Date().getTime();
prevTime = timestamp;
endTime = new Date().getTime();
}
requestRef = requestAnimationFrame(animate);
};

requestRef = requestAnimationFrame(animate);

``````// 慢太多了，就立刻执行下一个循环
if (nextTime < 0) {
nextTime = 0;
}

``````// 慢到一定临界点，比正常循环的时间数稍微慢点，再执行下一个循环
if (nextTime < 900) {
nextTime = 900;
}

### 结语

「不再迷茫！看了这篇文章让你上手Vue3.0开发有丝滑般体验」

「看一眼，Vue3 script-setup语法糖下组件通信就学会了（附源码）」

「超详细！监听微信小程序五种切后台情况」