在js中如果打算使用setInterval進(jìn)行倒數(shù),計(jì)時(shí)等功能,往往是不準(zhǔn)確的,因?yàn)閟etInterval的回調(diào)函數(shù)并不是到時(shí)后立即執(zhí)行,而是等系統(tǒng)計(jì)算資源空閑下來(lái)后才會(huì)執(zhí)行.而下一次觸發(fā)時(shí)間則是在setInterval回調(diào)函數(shù)執(zhí)行完畢之后才開(kāi)始計(jì)時(shí),所以如果setInterval內(nèi)執(zhí)行的計(jì)算過(guò)于耗時(shí),或者有其他耗時(shí)任務(wù)在執(zhí)行,setInterval的計(jì)時(shí)會(huì)越來(lái)越不準(zhǔn),延遲很厲害.
下面的代碼可以說(shuō)明這個(gè)問(wèn)題
復(fù)制代碼 代碼如下:
var startTime = new Date().getTime();
var count = 0;
//耗時(shí)任務(wù)
setInterval(function(){
var i = 0;
while(i++ < 100000000);
}, 0);
setInterval(function(){
count++;
console.log(new Date().getTime() - (startTime + count * 1000));
}, 1000);
復(fù)制代碼 代碼如下:
176
340
495
652
807
961
1114
1268
1425
1579
1734
1888
2048
2201
2357
2521
2679
2834
2996
......
復(fù)制代碼 代碼如下:
var startTime = new Date().getTime();
var count = 0;
setInterval(function(){
var i = 0;
while(i++ < 100000000);
}, 0);
function fixed() {
count++;
var offset = new Date().getTime() - (startTime + count * 1000);
var nextTime = 1000 - offset;
if (nextTime < 0) nextTime = 0;
setTimeout(fixed, nextTime);
console.log(new Date().getTime() - (startTime + count * 1000));
}
setTimeout(fixed, 1000);
復(fù)制代碼 代碼如下:
186
200
230
271
158
899
900
899
900
899
899
899
902
899
418
202
232
266
145
174
192
214
242
268
149
179
214
......
新聞熱點(diǎn)
疑難解答
圖片精選