Is the setInterval() an asynchronous function?

Junior picture Junior · Sep 2, 2015 · Viewed 29.3k times · Source

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

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

For example, if one XMLHttpRequest request 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?

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

Answer

MinusFour picture MinusFour · Sep 2, 2015

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.