[英]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.