Tim
Tim

Reputation: 2411

Javascript - How can I wait 10 seconds for a promise to return?

I'm trying to see a response between each HTTP request by using a while loop but this causes my browser to freak out and making me force quit it. Can someone give me some pointers here? I'm attempting to send a "wake up" command and if it's asleep I get a 408 error and if it's awake I get a 200 OK. I'm thinking that maybe I should add like a sleep function for 10 seconds between each http request but I don't think there is a simple "sleep" function like there is in Python.

state = "asleep"
while (state === "asleep") {
     this.wakeUp(user).then(function (response) {
          if (response.status === 200):
              state = "awake";
      });
    }

wakeUpVehicle(user) {
    return new Promise(function(resolve) {
      fetch(url + "/wake_up", {
        method: "post",
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer " + access_token
        }
      })
      .then(res => res.json())
      .then(json => {resolve(json["response"])})
    });
  }

I would appreciate any help! :-) Thanks

Upvotes: 1

Views: 1402

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138257

There is no simple "sleep", but you can easily write that yourself:

 const timer = ms => new Promise(res => setTimeout(res, ms));

Then it is as easy as:

 let state = "asleep"; // always declare variables!

 (async function polling() { // leave the synchronous track
   while(true) { // async infinite loops are not as bad as they might seem
     const response = await wakeUp(user);
     state = response.status ? "awake" : "asleep"; // not sure if this is what you wanted, edit according to your needs
     await timer(10 * 1000); // wait for 10secs before checking again
  }
})();

Upvotes: 6

Related Questions