在一个页面中可以同时设置多少个 javascript setTimeout/ setInterval 调用?

发布于 2024-12-02 16:19:51 字数 78 浏览 1 评论 0原文

我必须使用至少 2 个 setTimeouts 和 1 个 setInterval。这是否依赖于所使用的浏览器或 JavaScript 引擎?

I have to use atleast 2 setTimeouts and 1 setInterval. Does this have any dependency on the browser or javascript engine being used?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

南烟 2024-12-09 16:19:51

tl;dr:在创建 100K 个计时器之前,不要担心计时器的成本。

我刚刚通过创建此测试文件(一遍又一遍地创建 100K 计时器)对计时器性能进行了快速测试:

<script>
var n = 0; // Counter used to verify all timers fire

function makeTimers() {
  var start = Date.now();
  for (var i = 0; i < 100000; i++, n++) {
    setTimeout(hello, 5000);
  }
  console.log('Timers made in', Date.now() - start, 'msecs');
}

function hello() {
  if (--n == 0) {
    console.log('All timers fired');
    makeTimers(); // Do it again!
  }
}

setTimeout(makeTimers, 10000);  // Wait a bit before starting test
</script>

我在大约 2014 年 Macbook Pro 上的 Google Chrome (v54) 中打开了此文件,然后转到开发人员工具中的“时间轴”选项卡并记录页面加载时的内存配置文件并运行 3-4 个测试周期。

观察

计时器创建循环需要 200 毫秒。预测试页堆大小从 3.5MB 开始,最终稳定在 3.9MB。

结论

每个计时器的设置时间约为 0.002 毫秒,并向 JS 堆添加约 35 个字节。

tl;dr: Don't worry about the cost of timers until you're creating 100K's of them.

I just did a quick test of timer performance by creating this test file (creates 100K timers over and over):

<script>
var n = 0; // Counter used to verify all timers fire

function makeTimers() {
  var start = Date.now();
  for (var i = 0; i < 100000; i++, n++) {
    setTimeout(hello, 5000);
  }
  console.log('Timers made in', Date.now() - start, 'msecs');
}

function hello() {
  if (--n == 0) {
    console.log('All timers fired');
    makeTimers(); // Do it again!
  }
}

setTimeout(makeTimers, 10000);  // Wait a bit before starting test
</script>

I opened this file in Google Chrome (v54) on my circa ~2014 Macbook Pro, and went to the Timeline tab in Developer Tools and recorded the memory profile as the page loaded and ran thru 3-4 cycles of the test.

Observations

The timer creation loop takes 200ms. The page heap size starts at 3.5MB pre-test, and levels out at 3.9MB.

Conclusion

Each timer takes ~.002 msecs to set up, and adds about 35 bytes to the JS heap.

魔法少女 2024-12-09 16:19:51

在一个页面上,您可以根据需要同时运行任意多个 setTimeouts/setIntervals,但是为了单独控制每个设置,您需要将它们分配给一个变量。

var interval_1 = setInterval("callFunc1();",2000);
var interval_2 = setInterval("callFunc2();",1000);
clearInterval(interval_1);

上面的代码同样适用于setTimeout,只是替换了措辞。

正如 Kevin 所说,JavaScript 确实是单线程的,所以虽然你可以同时有多个计时器计时,但任何时候只有一个可以触发 - 即,如果你有一个触发一个在执行中“停止”的函数,例如一个警报框,那么我相信该 JS 必须“恢复”,然后另一个才能触发。

下面给出另一个例子。虽然标记无效,但它显示了超时的工作原理。

<html>
    <body>
        <script type="text/javascript">
            function addThing(){
                var newEle = document.createElement("div");
                newEle.innerHTML = "Timer1 Tick";
                document.body.appendChild(newEle);
            }   
            var t1= setInterval("addThing();",1000);
            var t2 = setInterval("alert('moo');",2000);
        </script>
    </body>
</html>

On a page you can have as many setTimeouts/setIntervals running at once as you wish, however in order to control each individually you will need to assign them to a variable.

var interval_1 = setInterval("callFunc1();",2000);
var interval_2 = setInterval("callFunc2();",1000);
clearInterval(interval_1);

The same code above applies to setTimeout, simply replacing the wording.

As Kevin has stated, JavaScript is indeed single threaded, so while you can have multiple timers ticking at once, only one can fire at any one time - i.e. if you have one that fires a function which 'halts' in execution, for example with an alert box, then that JS must be 'resumed' before another can trigger I believe.

One further example is given below. While the markup is not valid, it shows how timeouts work.

<html>
    <body>
        <script type="text/javascript">
            function addThing(){
                var newEle = document.createElement("div");
                newEle.innerHTML = "Timer1 Tick";
                document.body.appendChild(newEle);
            }   
            var t1= setInterval("addThing();",1000);
            var t2 = setInterval("alert('moo');",2000);
        </script>
    </body>
</html>
巾帼英雄 2024-12-09 16:19:51

您可以根据需要使用多个。请记住,JavaScript 是单线程的,因此它们都不能并行执行。

You can use as many as you want. Just remember that JavaScript is single threaded, so none of them can execute in parallel.

谁的年少不轻狂 2024-12-09 16:19:51

var Interval_1 = setInterval("callFunc1();",2000); 调用 eval() 这是邪恶的,所以它是坏的。
使用这个 var Interval_1 = setInterval(callFunc1,2000);

对于这个问题,你可以使用任意多个,但如果两个操作之间的间隔相同,你最好这样做

var interval = setInterval(function() {
  // function1
  fct1(); 
  // function2
  fct2();
 },2000);

var interval_1 = setInterval("callFunc1();",2000); calls eval() which is evil so it's BAD.
Use this instead var interval_1 = setInterval(callFunc1,2000);

And for the question, you may use as many as you want but if all have the same interval between two actions, you better do it this way

var interval = setInterval(function() {
  // function1
  fct1(); 
  // function2
  fct2();
 },2000);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文