setTimeout或setInterval是否使用线程来触发? [英] Does setTimeout or setInterval use thread to fire?

查看:271
本文介绍了setTimeout或setInterval是否使用线程来触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读这篇文章,但每个worker也是单线程的)。但是,当谈到环境的API时,JavaScript并不是唯一可行的方法。 setTimeout setInterval addEventListener 等函数本机实现(或者,至少在单线程JavaScript之外),它们的回调由环境触发,例如浏览器。将这些回调放入队列的环境是由单线程JavaScript引擎执行的。这就是浏览器能够接受触发的新点击事件的方式,即使它仍在执行其他一些JavaScript代码。这就是JavaScript被视为事件驱动的原因。


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?

解决方案

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.

这篇关于setTimeout或setInterval是否使用线程来触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆