1

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?

  • "will the callback function in the callback queue waits for 11 sec to be executed?" - yes, well, if you mean "after the 10 seconds" with it. This is easy to test btw: `let start = performance.now(); setTimeout(() => void console.log(\`timer executed after ${performance.now() - start}ms.\`), 2000); while(performance.now() - start < 10000); console.log('busy waiting finished.');` – ASDFGerte Mar 22 '21 at 12:32
  • I completely understand wanting to check the underlying theory, but it's still worth doing (and sharing) your empirical test of your thought -- e.g., code doing it and observing how long it takes for the timer to fire. – T.J. Crowder Mar 22 '21 at 12:42

2 Answers2

1

...will the callback function in the callback queue waits for 11 sec to be executed?

Not necessarily 11 seconds, no; it'll run soon after the 10-second synchronous code completes. The length of the timer doesn't matter if it's shorter than the synchronous code duration. More details in this page on how the Node.js event loop works.

For example, with this code:

function elapsed(start) {
    const elapsed = Date.now() - start;
    return `${(elapsed / 1000).toFixed(4)}s`;
}
const startTimer = Date.now();
console.log(`Starting timer`);
setTimeout(() => {
    console.log(`Timer fired after ${elapsed(startTimer)}`);
}, 2000);
const finish = Date.now() + 10000;
const startBusyWait = Date.now();
console.log(`Starting to wait`);
while (Date.now() < finish) {
    // Busy-wait -- DON'T DO THIS
}
console.log(`Done busy-waiting after ${elapsed(startBusyWait)}`);

you'll see something like:

Starting timer
Starting to wait
Done busy-waiting after 10.0000s
Timer fired after 10.0050s
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

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

pouria
  • 949
  • 8
  • 21
  • @RahulRNair You're welcome. I appreciate it if you mark it as the accepted answer if it helped you – pouria Mar 22 '21 at 14:36