I have been reading this article http://ejohn.org/blog/how-javascript-timers-work/ and how setTimeout
and setInterval
and other async tasks such as button click confused me a little.
I know that JS is a single threaded, that means, AFAIK, all the callback functions (a.k.a. event handlers) will be queued and executed in order. However, look at the image below that I took from the article, linked above:
Each block represents some work, and - at around 10ms - the timer gets fired. I know that its callback function is put on the queue for later execution, but how come the event can get called while something is being executed already?
Is it because setTimeout()
starts using a separate thread to count the time internally and fire its completion event?
Please, note that I am not talking about its callback execution here; rather, I am trying to understand how setTimeout
can count the time and fires its completion. I know that its callback will be called not before its given time parameters, but maybe later but this is because its callback is queued to later time when the runtime finds some time to check whether there is anything to execute in the queue.
Similar to this question, how come browsers accepts new click to be registered while - let's say - a loop is working behind the scenes at the moment of user click?
If you say browsers maintain different threads for different things, then can we call JS in browsers single threaded?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…