Javascript setInterval 是 CPU 密集型的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6650134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:37:39  来源:igfitidea点击:

Is setInterval CPU intensive?

javascriptajaxcpusetinterval

提问by Ryuku

I read somewhere that setInterval is CPU intensive. I created a script that uses setInterval and monitored the CPU usage but didn't notice a change. I want to know if there is something I missed.

我在某处读到 setInterval 是 CPU 密集型的。我创建了一个使用 setInterval 的脚本并监控 CPU 使用情况,但没有注意到变化。我想知道是否有我遗漏的东西。

What the code does is check for changes to the hash in the URL (content after #) every 100 milliseconds and if it has changed, load a page using AJAX. If it has not changed, nothing happens. Would there be any CPU issues with that.

代码的作用是每 100 毫秒检查一次 URL 中的哈希值(# 之后的内容)是否发生更改,如果发生更改,则使用 AJAX 加载页面。如果它没有改变,则什么都不会发生。会不会有任何 CPU 问题。

采纳答案by lonesomeday

I don't think setIntervalis inherently going to cause you significant performance problems. I suspect the reputation may come from an earlier era, when CPUs were less powerful.

我认为setInterval本质上不会给您带来重大的性能问题。我怀疑这种声誉可能来自更早的时代,当时 CPU 的功能不那么强大。

There are ways that you can improve the performance, however, and it's probably wise to do them:

然而,有一些方法可以提高性能,这样做可能是明智的:

  1. Pass a function to setInterval, rather than a string.
  2. Have as few intervals set as possible.
  3. Make the interval durations as long as possible.
  4. Have the code running each time as short and simple as possible.
  1. 将函数传递给setInterval,而不是字符串。
  2. 设置尽可能少的间隔。
  3. 使间隔持续时间尽可能长。
  4. 让每次运行的代码尽可能简短。

Don't optimise prematurely -- don't make life difficult for yourself when there isn't a problem.

不要过早地优化——不要在没有问题的情况下让自己的生活变得困难。

One thing, however, that you can do in your particular case is to use the onhashchangeevent, rather than timeouts, in browsers that support it.

但是,您可以在特定情况下做的一件事是onhashchange在支持它的浏览器中使用该事件,而不是超时。

回答by jAndy

I would rather say it's quite the opposite. Using setTimeoutand setIntervalcorrectly, can drastical reduce the browsers CPU usage. For instance, using setTimeoutinstead of using a foror whileloop will not only reduce the intensity of CPU usage, but will also guarantee that the browser has a chance to update the UI queue more often. So long running processes will not freeze and lockup the user experience.

我宁愿说情况恰恰相反。使用setTimeoutsetInterval正确的,可以大刀阔斧的减少浏览器的CPU占用率。例如,使用or循环setTimeout代替使用不仅会降低 CPU 使用的强度,还会保证浏览器有机会更频繁地更新 UI 队列。因此长时间运行的进程不会冻结和锁定用户体验。forwhile

But in general, using setIntervalreally like a lot on your site may slow down things. 20 simultaneously running intervals with more or less heavy work will affect the show. And then again.. you really can mess up any part I guess that is not a problem of setInterval.

但总的来说,setInterval在您的网站上大量使用可能会减慢速度。20 个同时运行的间隔或多或少的繁重工作会影响表演。然后再说一遍..你真的可以搞砸我想这不是问题的任何部分setInterval

..and by the way, you don't need to check the hash like that. There are events for that:

..顺便说一句,你不需要像那样检查哈希。有一些事件:

onhashchange

will fire when there was a change in the hash.

当哈希值发生变化时会触发。

window.addEventListener('hashchange', function(e) {
    console.log('hash changed, yay!');
}, false);

回答by aroth

No, setIntervalis not CPU intensive in and of itself. If you have a lot of intervals running on very short cycles (or a very complex operation running on a moderately long interval), then thatcan easily become CPU intensive, depending upon exactly what your intervals are doing and how frequently they are doing it.

不,setInterval它本身并不是 CPU 密集型的。如果你有很多间隔在很短的周期内运行(或者一个非常复杂的操作以中等长的间隔运行),那么很容易成为 CPU 密集型的,这取决于你的间隔正在做什么以及他们这样做的频率。

I wouldn't expect to see any issues with checking the URL every 100 milliseconds on an interval, though personally I would increase the interval to 250 milliseconds, just because I don't expect that the difference between the two would be noticeable to a typical user and because I generally try to use the longest timeout intervals that I think I can get away with, particularly for things that are expected to result in a no-op most of the time.

我不希望每隔 100 毫秒检查一次 URL 会出现任何问题,尽管我个人会将时间间隔增加到 250 毫秒,只是因为我不希望这两者之间的差异对于典型的人来说会很明显用户,因为我通常尝试使用最长的超时间隔,我认为我可以逃脱,特别是对于大多数情况下预计会导致无操作的事情。

回答by user703016

There's a bit of marketing going there under the "CPU intensive" term. What it really means is "more CPU intensive than some alternatives". It's not "CPU intensive" as in "uses a whole lot of CPU power like a game or a compression algorithm would do".

在“CPU 密集型”术语下有一些营销活动。它的真正含义是“比某些替代方案更占用 CPU”。它不是“CPU 密集型”,因为“像游戏或压缩算法一样使用大量 CPU 能力”。

Explanation :

解释 :

Once the browser has yielded control it relies on an interrupt from the underlying operating system and hardware to receive control and issue the JavaScript callback. Having longer durations between these interrupts allows hardware to enter low power states which significantly decreases power consumption. By default the Microsoft Windows operating system and Intel based processors use 15.6ms resolutions for these interrupts (64 interrupts per second). This allows Intel based processors to enter their lowest power state. For this reason web developers have traditionally only been able to achieve 64 callbacks per second when using setTimeout(0) when using HTML4 browsers including earlier editions of Internet Explorer and Mozilla Firefox.

Over the last two years browsers have attempted to increase the number of callbacks per second that JavaScript developers can receive through the setTimeout and setInterval API's by changing the power conscious Windows system settings and preventing hardware from entering low power states. The HTML5 specification has gone to the extreme of recommending 250 callbacks per second. This high frequency can result in a 40% increase in power consumption, impacting battery life, operating expenses, and the environment. In addition, this approach does not address the core performance problem of improving CPU efficiency and scheduling.

一旦浏览器获得控制权,它就会依赖来自底层操作系统和硬件的中断来接收控制权并发出 JavaScript 回调。在这些中断之间具有更长的持续时间允许硬件进入低功耗状态,从而显着降低功耗。默认情况下,Microsoft Windows 操作系统和基于 Intel 的处理器对这些中断使用 15.6 毫秒的分辨率(每秒 64 个中断)。这允许基于 Intel 的处理器进入其最低功耗状态。因此,在使用 HTML4 浏览器(包括早期版本的 Internet Explorer 和 Mozilla Firefox)时,Web 开发人员在使用 setTimeout(0) 时,传统上只能实现每秒 64 次回调。

在过去的两年中,浏览器试图通过更改具有功耗意识的 Windows 系统设置并防止硬件进入低功耗状态,来增加 JavaScript 开发人员可以通过 setTimeout 和 setInterval API 接收的每秒回调数。HTML5 规范已经达到了推荐每秒 250 个回调的极端。这种高频率会导致功耗增加 40%,从而影响电池寿命、运营费用和环境。此外,这种方式并没有解决提高CPU效率和调度的核心性能问题。

From http://ie.microsoft.com/testdrive/Performance/setImmediateSorting/Default.html

来自http://ie.microsoft.com/testdrive/Performance/setImmediateSorting/Default.html

回答by Sarath

In your case there will not be any issue. But if your doing some huge animations in canvas or working with webgl , then there will be some CPU issues, so for that you can use requestAnimationFrame.

在你的情况下不会有任何问题。但是如果你在画布上做一些巨大的动画或者使用 webgl ,那么就会有一些 CPU 问题,因此你可以使用 requestAnimationFrame。

Refer this link About requestAnimationFrame

请参阅此链接关于 requestAnimationFrame

回答by huseyin tugrul buyukisik

Function time > interval time is bad, you can't know when cpu hiccups or is slow one and it stacks on top of ongoing functions until pc freezes. Use settimeout or even better, process.nextick using a callback inside a settimeout.

函数时间 > 间隔时间很糟糕,你无法知道 cpu 何时打嗝或缓慢,它会叠加在正在进行的函数之上,直到 pc 冻结。使用 settimeout 或更好的 process.nextick 在 settimeout 中使用回调。