0

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?

Mickael B.
  • 4,755
  • 4
  • 24
  • 48
Prabin Upreti
  • 498
  • 5
  • 16
  • Maybe this helps you? https://stackoverflow.com/questions/39879/why-doesnt-javascript-support-multithreading – bill.gates Jan 13 '20 at 19:16
  • Timeouts are handled by delegating them to the asynchronous timer capabilities of the operating system :-) But sure, there could also be a busy-spinning background thread waiting for timer registrations, queuing them up, and pushing the callbacks to the event loop's event queue once they expire. – Bergi Jan 13 '20 at 19:34

0 Answers0