# 我的这段js倒计时为什么越走越慢？

995 次浏览
``````var orderTimeOut = 900000;
var timer = setInterval(() => {
orderTimeOut -= 10;
if (orderTimeOut > 10) {
times = overTime(orderTimeOut);
console.log(times)
}else {
orderTimeOut = 0;
times = "00:00:00";
}
}, 10);

function overTime(time) {
var a = (time % 1000).toString().substr(0, 2);
var b = Math.floor(time / 1000);
var m = b % 60;
m = String(m);
m = m.length >= 2 ? m : "0" + m;
var f = Math.floor(time / (1000 * 60));
f = String(f);
f = f.length >= 2 ? f : "0" + f;
return f + ":" + m + "." + a;
}``````

Demo_Hu 462
2018-05-25 提问
2 个回答

``````let i = 0;
setInterval(() => {
if (i === 0) {
console.log('start', Date.now())
let lastTime = new Date().getTime() + 10 * 1000;//暂停10s
while (lastTime > new Date().getTime()) {

}
}
i++;
console.log(i, Date.now())//以后的时间都延迟了10s+

}, 1000)``````

`setInterval`，浏览器会单独开一个线程，每隔几毫秒将此方法扔进`JS`队列。

1

``````let timeTotal = 30000;
let timePrevious = Date.now();

printTime();
disturbFunction();

function printTime() {
let timeNow = Date.now();
let timeJap = timeNow - timePrevious;
let timeLeft = timeTotal - timeJap;

timePrevious = timeNow;

if (timeLeft > 0) {
setTimeout(() => printTime(), 500);
console.log('Jap:', timeJap, '. Left:', timeLeft);
} else {
console.log('Jap:', timeJap, '. Left:', 0);
}
}

function disturbFunction() {
let i = 100000;
while (i--) {
JSON.parse(JSON.stringify({}));
}
setTimeout(() => disturbFunction(), 100);
}``````

wmaker · 2018年06月12日