setInterval()是一个异步函数吗?

Jun*_*ior 8 javascript jquery asynchronous xmlhttprequest setinterval

XMLHttpRequest每秒都在服务器上,服务器将响应新消息.要调用XMLHttpRequest每一秒我使用a中的setInterval()函数SharedWorker.

但是,由于我每秒都在提出请求,我想知道是否setInterval()异步?

例如,如果一个XMLHttpRequest请求花了3秒钟来完成"由于延迟",我是否会同时setInterval()发出3个请求,或者等到第一个请求完成之后再等待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);
Run Code Online (Sandbox Code Playgroud)

spe*_*der 5

是的,你会遇到麻烦的。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') 
Run Code Online (Sandbox Code Playgroud)


Min*_*our 5

如前所述,它不会等到请求完成。这是一种间隔承诺的方法:

 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);
Run Code Online (Sandbox Code Playgroud)

它将继续增加每秒请求的数量,但是如果超过1秒,它将延迟自身。