Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

javascript - Does setTimeout or setInterval use thread to fire?

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:

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JavaScript is single threaded, which means that two pieces of JavaScript will not execute at the same time (unless using a worker, but each worker is also single-threaded). But JavaScript isn't the only thing at play when it comes to the environment's API's. Functions like setTimeout, setInterval and addEventListener are implemented natively (or, at-least, outside of the single-threaded JavaScript), and their callbacks are triggered by the environment, such as a browser. It is the environment that puts these callbacks onto the queue, to be executed by the single threaded JavaScript engine. This is how the browser is able to accept new click events to be fired, even though it is still executing some other JavaScript code. This is the reason JavaScript is considered event-driven.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...