I know that javascript is single-threaded, meaning javascript runtime (browser or Node, etc) will send time taking tasks to the event loop so that the execution runs smoothly without blocking on the thread it has. But I am a bit confused about how runtime decides what goes to the event loop. (what is some code block has to do to get into the event loop). This may be because of my lack of understanding, but anyway I will elaborate my question with an example.
function first() {
console.log('first');
}
function second() {
console.log('second');
}
first()
let i=0;
while(i<1000000000000){
i++
}
second();
In this senario console prints 'first' then takes huge amount of time (probbly stuck) and prints 'second'. So that while code block is not going in to the event loop.
function first() {
console.log('first');
}
function second() {
console.log('second');
}
first()
setTimeout(()=>{},500000);
second();
Here it is not the case, First, it prints 'first' then load setTimeout to the stack, but it takes time, so moves it into the event loop, continue the thread, and prints 'second'. After 500000 ms it setTime will return to the call stack hence the thread.
So I'd like to know why "while block" doesn't go into the event loop but setTimeout does. Is it because, setTimeout is an asynchronous call?. But still how would runtime know it's asynchronous?