Is setInterval () an asynchronous function?

I do XMLHttpRequest every second to the server, the server will respond with new messages. To call XMLHttpRequest every second, I use the setInterval() function inside SharedWorker .

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

For example, if one XMLHttpRequest request took 3 seconds to complete β€œdue to a delay”, will I have three requests at the same time or will setInterval() wait until the first request completes before it takes 1 second and send another request?

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); 
+6
source share
4 answers

As indicated, he will not wait until the request is completed. Here you can defer 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 continue to add queries to do every second, but it will be delayed if it passes more than 1 second.

+1
source

Yes, you have a problem. setInterval will work like a clock, regardless of the status of your requests.

You can start the timer with one hit using setTimeout at the end of each request ... like this:

 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') 
+2
source

setInterval simply queues the code to run after the completion of the current call stack. This may be useful for some things.

So, it is asynchronous in that it interrupts the synchronous thread, but in reality it will not run simultaneously / in a separate thread. If your goal is background processing, look at webmasters.

Thus, no matter how long the server takes, it will request every second, since your code is set to 1000

+1
source

yes setInterval and setTimeout are asynchronous, but you do not push, you pull if you want the push request to read about web sockets

0
source

All Articles