Javascript setInterval() 是异步函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32342601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:55:00  来源:igfitidea点击:

Is the setInterval() an asynchronous function?

javascriptjqueryasynchronousxmlhttprequestsetinterval

提问by Junior

I am making a XMLHttpRequestevery second to a server, the server will respond with new messages. To call the XMLHttpRequestevery second I use the setInterval()function inside of a SharedWorker.

XMLHttpRequest每秒钟都在向服务器发送消息,服务器将使用新消息进行响应。为了XMLHttpRequest每秒调用一次,我使用了setInterval()a 中的函数SharedWorker

However, since I am making a request every second, I would like to know if setInterval()is asynchronous or not?

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

For example, if one XMLHttpRequestrequest took 3 seconds to finish "due to a delay", will I have 3 requests going at the same time or will setInterval()wait until the first request completes before it waits 1 second and send another request?

例如,如果一个XMLHttpRequest请求“由于延迟”需要 3 秒才能完成,我是否会同时处理 3 个请求,还是会setInterval()等到第一个请求完成后再等待 1 秒并发送另一个请求?

Here is my code

这是我的代码

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);

采纳答案by MinusFour

As pointed out, it won't wait until the request is done. Here's a way to interval a promise:

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

 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);

It will keep on adding requests to do every second, but it will delay itself if it goes over 1 second.

它将继续增加每秒执行的请求,但如果超过 1 秒,它会延迟自身。

回答by spender

Yes, you'll run into trouble. setIntervalwill go off like clockwork, irrespective of the state of your requests.

是的,你会遇到麻烦。setInterval无论您的请求状态如何,都会像发条一样响起。

You're better-off starting a one hit timer using setTimeoutat the completion of every request... so:

你最好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') 

回答by sumeet kumar

setIntervalsimply queues the code to run once the current call stack is finished executing. This can be useful for some things.

setInterval一旦当前调用堆栈完成执行,只需将代码排队即可运行。这对某些事情很有用。

So yes, it's asynchronous in that it breaks the synchronous flow, but it's not actually going to execute concurrently/on a separate thread. If your goal is background processing, have a look at webworkers.

所以是的,它是异步的,因为它打破了同步流程,但它实际上不会并发/在单独的线程上执行。如果您的目标是后台处理,请查看 webworkers。

So regardless of how much time server takes it will request every second as per your code is set for 1000

因此,无论服务器花费多少时间,它都会根据您的代码设置为 1000 每秒请求一次

回答by VEga

yes the setInterval & setTimeout are asyncronous, but you not do a push, you do a pull, if you want a push request read about of web sockets

是的,setInterval 和 setTimeout 是异步的,但是如果您想要读取有关 Web 套接字的推送请求,则不是进行推送,而是进行拉取