1

I have this while loop in JS. It tries to do something and if it doesn't work, I want it to calculate the time it will need to wait and then reloop.

while (makeSomething() == false) {
    var wait = a + b + c;
    sleep(wait);
}

I only know setTimeout(), but as you might know it does not behave like I want it to do.

If jQuery offers a solution for it, that would be okay too.

Cutaraca
  • 696
  • 2
  • 8
  • 15

2 Answers2

3

You are going to have to change how your logic works. Probably means you need to break up your code. Basic idea of what you want to do it:

function waitForIt(){
   if(makeSomething() == false) {
        var wait = a + b + c;
        window.setTimeout(waitForIt, wait);
   } else {
       console.log("do next step");
   }
}
waitForIt();
epascarello
  • 185,306
  • 18
  • 175
  • 214
0

It depends on your intention here. From your question, it seems you want to stay in the while loop until makeSomething() is true. epascarello's answer will continue thread execution because it uses setTimeout().

Technically his answer is significantly better because it does not hang the application. But if you really wanted a sleep function that will stop all application processing you can use this function:

    function sleepFor( sleepDuration ) {
        var now = new Date().getTime();
        while(new Date().getTime() < now + sleepDuration){ /* do nothing */ } 
    }

Note that this is generally bad practice, a user will not be able to interact with your application while the thread is asleep.

Gathered from: What is the JavaScript version of sleep()?

Community
  • 1
  • 1
Ravvy
  • 199
  • 7
  • this really seems to be the only possibility, thank you – Cutaraca Nov 20 '15 at 19:02
  • You're welcome. I'd appreciate it if you could mark my answer as correct if you thought it was. – Ravvy Nov 20 '15 at 19:05
  • To downvoters: I'd be grateful for any feedback or criticism that I can learn from or use to help me improve my answer. – Ravvy Nov 20 '15 at 19:14
  • (I am not a downvoter) I don't understand your phrase: "But if you really wanted ... stop all application processing". What is the use case? CPU burn test, kill app GUI or what? – Dzenly Nov 20 '15 at 19:21
  • There aren't many use cases where this is useful to be honest. It should only be strictly used for testing purposes. See the StackOverflow link in my answer for more information. – Ravvy Nov 20 '15 at 19:30