Learning question in js at node.js , isn't it asynchronous?

Viewed 24

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?");
1 Answers

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.

Related