I have following code in javascript :
var x = 1;
console.log('printing x'+x);
setTimeout(()=>{console.log("first timeout")},2000);
setTimeout(()=>{console.log("second timeout")},0);
I know that 'second timeout' is printed before 'first timeout'.
I understand the event loop and asynchronous behavior in javascript but i have a huge confusion in how browser apis: where all this asynchronous functions like setTimeout()
and ajax requests are registered, executes this functions in parallel.
I know that this browser api is written in c++ so can be multi threaded but i am not sure 100% if it is.
For example in above code setTimeout((),2000)
is registered first in browser api and the timer function starts executing it. Later setTimeout((),0)
is registered while the first setTimeout
is still being executed. Here to get the result from second setTimeout
the browser api must share the timer or delay mechanism or resource so that the result from the secondTimeout is put first in the callback queue.
So my question in short is, is browser api multi threaded? If not, how it handles my concern?