JS中的计时 - 多个setIntervals同时运行并同时启动? [英] Timing in JS - multiple setIntervals running at once and starting at the same time?

查看:132
本文介绍了JS中的计时 - 多个setIntervals同时运行并同时启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个功能:

myFunc = function(number) {
  console.log("Booyah! "+number);
}

我想让它在设定的时间间隔内运行。听起来我应该使用 setInterval ,呵呵!

And I want it to run on a set interval. Sounds like I should use setInterval, huh!

但是如果我想运行相同函数的多个区间,所有这些区间都在同一时间开始呢?

But what if I want to run multiple intervals of the same function, all starting at the exact same time?

setInterval(function(){
  myFunc(1);
}, 500);

setInterval(function(){
  myFunc(2);
}, 1000);

setInterval(function(){
  myFunc(3);
}, 2000);

这样第一次运行的时间恰好是第二次运行一次所需的两次,并且相同在第二和第三之间。

So that the first runs exactly twice in the time it takes the second to run once, and the same between the second and third.

你如何确保它们全部同时开始以便它们同步?

How do you make sure that they all start at the same time so that they are in sync?

推荐答案

好问题,但在JS中你不能。要在同一程序中执行多个功能,您需要同时执行多线程和一些深度计时和线程处理技能。 JS是单线程的。 setInterval 在延迟之后没有实际运行该函数,而是在延迟之后它将函数添加到事件堆栈以便在处理器可以运行时立即运行。如果proc忙于另一个操作,则实际运行所需的时间将比延迟时间长。多个间隔/超时都会添加对同一事件堆栈的调用,因此它们会在proc可用时依次运行。

Good question, but in JS you can't. To have multiple functions in the same program execute at the same time you need multi-threading and some deep timing and thread handling skills. JS is single threaded. setInterval doesn't acutally run the function after the delay, rather after the delay it adds the function to the event stack to be run as soon as the processor can get to it. If the proc is busy with another operation, it will take longer than the delay period to actually run. Multiple intervals/timeouts are all adding calls to the same event stack, so they run in turn as the proc is available.

这篇关于JS中的计时 - 多个setIntervals同时运行并同时启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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