最近,我遇到了一個需求是我要隔段時間調(diào)用一個函數(shù),類似每隔十秒鐘發(fā)送一個 ajax 請求.當(dāng)然,setInterval 看起來是不錯的方式.但是我遇到了挫折.
想要理解為啥 setInterval 是不好的,我們需要在腦子里面知道一個知識,那就是 JavaScript 是單線程的.也就是一次只能執(zhí)行一個操作.
var fakeCallToServer = function() {
setTimeout(function() {
console.log('returning from server', new Date().toLocaleTimeString());
}, 4000);
}
setInterval(function(){
let insideSetInterval = new Date().toLocaleTimeString();
console.log('insideSetInterval', insideSetInterval);
fakeCallToServer();
}, 2000);
//insideSetInterval 14:13:47
//insideSetInterval 14:13:49
//insideSetInterval 14:13:51
//returning from server 14:13:51
//insideSetInterval 14:13:53
//returning from server 14:13:53
//insideSetInterval 14:13:55
//returning from server 14:13:55
正如你在打印的console.log語句中所看到的那樣,setInterval一直在不停地發(fā)送ajax調(diào)用而不關(guān)心先前的調(diào)用是否已經(jīng)返回。
這個會使得很多請求在排隊.
現(xiàn)在讓我們看下同步請求在 setInterval:
var counter = 0;
var fakeTimeIntensiveOperation = function() {
for(var i =0;i<50000000;i++) {
document.getElementById('random');
}
let insideTimeTakinngFunction = new Date().toLocaleTimeString()
console.log('insideTimeTakingFunction', insideTimeTakingFunction);
}
var timer = setInterval(function(){
let insideSetInterval = new Date().toLocaleTimeString();
console.log('insideSetInterval', insideSetInterval);
counter++;
if(counter == 1){
fakeTimeIntensiveOperation();
}
if (counter >= 5) {
clearInterval(timer);
}
}, 1000);
//insideSetInterval 13:50:53
//insideTimeTakingFunction 13:50:55
//insideSetInterval 13:50:55 <---- not called after 1s
//insideSetInterval 13:50:56
//insideSetInterval 13:50:57
//insideSetInterval 13:50:58
我們在這里看到當(dāng)setInterval遇到時間密集型操作時,它會做兩件事情中的任何一件,a 嘗試進入軌道或b創(chuàng)建新的節(jié)奏。 在Chrome上,它創(chuàng)造了一種新的節(jié)奏。
同樣,在 setInterval 的代碼塊里面遇到錯誤,它不會停止執(zhí)行而是繼續(xù)執(zhí)行錯誤的代碼,需要使用 clearInterval 來停止它.
或者,您可以在時間敏感操作的情況下遞歸使用setTimeout。
總結(jié)
在異步的操作里面,setTimeInterval 會創(chuàng)建一個長長的請求,
原文地址:
https://dev.to/akanksha_9560/why-not-to-use-setinterval--2na9