javascriptnode.jsloopssettimeoutsingle-threaded

In javascript, why doesn't the below code exit the loop?


let a = true;
setTimeout(() => {a = false}, 1000)
while(a){console.log(a)}

Solution

  • Let's see this step by step (if this was executed in browsers) :-

    let a = true;
    setTimeout(() => {a = false}, 1000)
    while(a){console.log(a)}
    

    The browser's Web API, this JavaScript execution stack and the event queue together forms our event loop for browsers.

    JavaScript is single-threaded (remember main thread ?) synchronous language. All the asynchronous behaviour that you see in your web apps or servers is because of the other parts which form the event loop.

    Also this is a simplified picture of it. There are more divisions to the event queue but that's beyond the scope of this question.