-2

I just started to learn Node.js and I need help: At the following code that runs on Node why it is stuck in a loop while it supposedly an asynchronous method? and also not waiting the interval.

class FuelBurner{
constructor(){
    console.log("construction set");
    this.fuel=0;
    this.rate=2.0;
    this.polluted=0.0;
}

run(){
    
    while (true){
        console.log("i run");
        setTimeout( function (){this.polluted+=this.rate},1000);
        this.fuel--;
        
    }
}

get_pollution(){
    return this.polluted;
}
}
console.log("Hello");
machine = new FuelBurner();
machine.run();
console.log("Why it never gets here?");
DanielGzgzz
  • 118
  • 1
  • 6
  • 1
    "*why it is stuck in a loop while it supposedly an asynchronous method?*" How *exactly* have you reached the conclusion that `FuelBurner.run()` itself is asynchronous and non-blocking? – esqew Sep 06 '22 at 18:07
  • while(true) is infinite and going to lock up your thread. That is not going to work. – epascarello Sep 06 '22 at 18:08
  • I supposed all functions are running asynchronously unless you use some declaration, thx for your answer then how you define sync and async in node , do you have a good link for me please? – DanielGzgzz Sep 06 '22 at 18:09
  • *"why it is stuck in a loop"* - What specifically do you expect `while (true)` to do? At what point do you expect that loop to exit and why? – David Sep 06 '22 at 18:09
  • related - https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep – James Sep 06 '22 at 18:19

1 Answers1

1

Asynchronous operations in JavaScript are put in a queue and only addressed by your code again when the main event loop isn't busy with something else.

You enter the while loop and pass a function to setTimeout.

Then the rest of the loop runs, and the loop starts again.

About a second later, the first timeout finishes and the function is put on the queue to run when the main event loop is free.

The main event loop is still running the while loop, and will do forever since the condition is always met. It never becomes free. It never pulls the function off the queue to run it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thx for the analysis ,Would you be kind to answer also if putting `await` to the time interval in the loop would solve it? or how it is made asynchronous – DanielGzgzz Sep 06 '22 at 18:16
  • @DanielGzgzz No. `while(true)` runs **forever** – Marc Sep 06 '22 at 18:20
  • `await` allows a function to go to sleep until a promise resolves. `setTimeout` does not return a promise (not does any of the rest of your code). – Quentin Sep 06 '22 at 18:23