[英]Is the setInterval() an asynchronous function?
我每秒都會向服務器發出一個XMLHttpRequest
,服務器會響應新的消息。 要每秒調用XMLHttpRequest
我在SharedWorker
使用setInterval()
函數。
但是,由於我每秒都在發出一個請求,我想知道setInterval()
是否是異步的?
例如,如果一個XMLHttpRequest
請求花了3秒鍾來完成“由於延遲”,我是否會同時進行3次請求,或者setInterval()
等到第一個請求完成之后再等待1秒並發送另一個請求?
這是我的代碼
function checkQueue(url)
{
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", reqListener);
xhr.open('GET', url, true);
xhr.send();
}
function reqListener ()
{
var queue = JSON.parse(this.responseText);
notifyAllPorts(queue);
console.log(this.responseText);
}
setInterval(
function() {
checkQueue('/add-ons/icws/push.php')
}
, 1000);
正如所指出的,它不會等到請求完成。 這是一種區分承諾的方法:
function checkQueue(url, cb) {
var xhr = new XMLHttpRequest();
xhr.addEventListener("loadend", cb);
xhr.addEventListener("load", reqListener);
xhr.open('GET', url, true);
xhr.send();
}
function reqListener ()
{
var queue = JSON.parse(this.responseText);
notifyAllPorts(queue);
console.log(this.responseText);
}
var promise = Promise.resolve(true);
setInterval(function () {
promise = promise.then(function () {
return new Promise(function (resolve) {
checkQueue(yourUrlHere, resolve);
});
});
}, 1000);
它將繼續添加每秒執行的請求,但如果超過1秒,它將自行延遲。
是的,你會遇到麻煩。 無論您的請求狀態如何, setInterval
都會像發條一樣關閉。
你最好在每個請求完成時使用setTimeout
啟動一個命中計時器......所以:
function checkQueue(url)
{
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", reqListener);
xhr.open('GET', url, true);
xhr.send();
}
function reqListener ()
{
var queue = JSON.parse(this.responseText);
notifyAllPorts(queue);
console.log(this.responseText);
setTimeout(
function() {
checkQueue('/add-ons/icws/push.php')
}, 1000);
}
checkQueue('/add-ons/icws/push.php')
setInterval
只是將代碼排隊,以便在當前調用堆棧執行完畢后運行。 這對某些事情很有用。
所以是的,它是異步的,因為它打破了同步流,但它實際上不會在一個單獨的線程上同時/執行。 如果您的目標是后台處理,請查看webworkers。
因此,無論服務器花費多少時間,它都會按照您的代碼設置為1000來每秒請求一次
是的,setInterval和setTimeout是異步的,但如果你想要讀取關於web套接字的推送請求,你就不要進行推送。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.