setInterval 和 setTimeout 如何工作? [英] How does setInterval and setTimeout work?
问题描述
我的处境很尴尬,
我使用纯 JavaScript 将近 3 年了,我知道 JavaScript 是单线程语言,并且您可以使用 setInterval
和 setTimeout
函数模拟异步执行,
I am working with pure JavaScript for almost 3 years, and I know that JavaScript is single-threaded language,
and that you can simulate asynchronous execution using setInterval
and setTimeout
functions,
但是当我想到它们如何工作时,我无法清楚地理解它.那么这些函数如何影响执行上下文?
but when I thought about how they can work I couldn't clearly understand it. So how these functions affect execution context?
我想在特定时间只运行一部分代码,然后切换到另一部分.如果是这样,那么很多 setInterval
或 setTimeout
调用会影响性能吗?
I suppose that in specific time runs only one part of the code and after it switches to
another part. If so, then would a lot of setInterval
or setTimeout
calls affect performance?
推荐答案
Javascript 是单线程的,但浏览器不是.浏览器至少有三个线程:Javascript引擎线程、UI线程和计时线程,其中setTimeout
和setInterval
的计时由计时线程完成.
Javascript is singled-threaded but the browser is not. The browser has at least three threads: Javascript engine thread, UI thread, and timing thread, where the timing of setTimeout
and setInterval
are done by the timing thread.
当调用setTimeout
或setInterval
时,浏览器中的计时器线程开始倒计时,时间到时将回调函数放入javascript 线程的执行堆栈中.回调函数不会在堆栈中位于其上方的其他函数完成之前执行.所以如果time up时还有其他耗时的函数在执行,setTimeout
的回调就不会及时完成.
When calling setTimeout
or setInterval
, a timer thread in the browser starts counting down and when time up puts the callback function in javascript thread's execution stack. The callback function is not executed before other functions above it in the stack finishes. So if there are other time-consuming functions being executed when time up, the callback of setTimeout
will not finish in time.
这篇关于setInterval 和 setTimeout 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!