怎样的setInterval和setTimeout的工作吗? [英] How does setInterval and setTimeout work?

查看:262
本文介绍了怎样的setInterval和setTimeout的工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是在一个尴尬的境地

我与纯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?

我想,在特定的时间只运行一个code的一部分,它切换到后
另一部分。如果是这样,那么将有很多的的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线程的执行栈回调函数。回调函数之前没有在堆栈中完成上面的其它功能的执行。因此,如果有时间的时候了,的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屋!

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