blade-sensei / learning

Roadmap for software engineer, sandbox, algorithms training, it also contains my daily task dashboard
9 stars 2 forks source link

setTimeout(callback, 0) is not exectued immediatly. This helps to undertands why Promise with asynchronous code run after, main loop. #39

Closed blade-sensei closed 4 years ago

blade-sensei commented 4 years ago
console.log('after callback');
setTimeout(() => console.log('timeout'), 0);
process.nextTick(() => console.log('tick'))
for (let i = 0; i < 100; i++) {
  console.log('test');
}

If we have this code. Main loop (JS thread) First after callback will be executed then seTimeout --> We go out and create another thread

Thread alternatives (timers, async etc)

Explanation

With this fact, and everything else, it all makes sense.

When f1() is encountered in the path of execution, the function is called and in it a setTimeout is called which has a callback which would be queued up for execution after 0 seconds has expired. Which should translate to immediate, but since the actual minimum is 4 milliseconds, the callback function is queued for execution after 4 milliseconds.

In this period, since JavaScript is non blocking, and in this particular case, this is not a I/O operation but a timeout, the preceding line, f2() gets executed. And this is why the output of f2() appears before f1():

source

First i thought that setime out was excuted after because the thread create by nodeJS or the browser is exectued un parallel or just after that setTimeout was executed so it lets the time to the JS main loop to take the next instruction and fill the call stack. THAT means the QUEUE job will be filled after that.. that means we will need to wait the end of the call stack.

BUT there is also another point, is that setTIme 0 has a REAL delay of 4ms (browser) or 1ms (node) depends on the env. and the case explained above is used.

The question now is if the REAL delay were 0ms.. is the callback be executed immediatly ? because the call stack of main JS thread will not have time to be filled ? OR maybe it depends of the time execution of each thread ( if the JS main thead is faster than the thread created for the async/or the env) it will be executed after.

blade-sensei commented 4 years ago

So. I did some mistakes. JS and event loops are running in the same thread. Just for few cases we run in another threads. setimeout schedule this but in the future. but immediatly we fill the stack.