Search code examples
javascriptnode.jsevent-loopsingle-threaded

how event loop exactly executes code in 2 seconds if the code is larger and call stack is not empty?


many explanations talk about call-stack being empty, but I don't get it, if we set a timer for 2 second and executes the code in an asynchronous manner, what if I have a code with run time of 10 sec and call-stack is not empty, will the callback function in the callback queue waits for 11 sec to be executed?


Solution

  • Yes. Imagine this code:

    setTimeout(function() {
      console.log('hi');
    }, 0);
    
    let i = 0;
    
    while (i <= 1e9) {
      i++;
    }

    What happens here?

    The code inside setTimeout is "postponed" to be run after 0ms "after the current call stack is empty".

    But the current script must finish its loop. So if you run this code, it will wait until i is counted to 1e9 before logging "hi" to the console.

    jsfiddle code