设置超时或设置间隔?

2022-01-29 00:00:00 javascript setinterval

据我所知,这两个 javascript 的行为方式相同:

As far as I can tell, these two pieces of javascript behave the same way:

选项 A:

function myTimeoutFunction()
{
    doStuff();
    setTimeout(myTimeoutFunction, 1000);
}

myTimeoutFunction();

选项 B:

function myTimeoutFunction()
{
    doStuff();
}

myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);

使用 setTimeout 和 有什么区别吗?a href="https://developer.mozilla.org/en-US/docs/Web/API/setInterval" rel="nofollow noreferrer">setInterval?

推荐答案

他们本质上试图做同样的事情,但是 setInterval 方法会比 setTimeout 方法,因为 setTimeout 等待 1000 毫秒,运行该函数,然后设置另一个超时.所以等待时间实际上比 1000 毫秒多一点(如果你的函数需要很长时间才能执行,那么等待时间会更长).

They essentially try to do the same thing, but the setInterval approach will be more accurate than the setTimeout approach, since setTimeout waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if your function takes a long time to execute).

虽然有人可能认为 setInterval 会精确 每 1000 毫秒执行一次,但需要注意的是,setInterval 也会延迟,因为 JavaScript 不是'不是多线程语言,这意味着 - 如果脚本的其他部分正在运行 - 间隔将不得不等待它完成.

Although one might think that setInterval will execute exactly every 1000ms, it is important to note that setInterval will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish.

在this Fiddle中可以很明显的看到timeout会落后,而interval是几乎所有时间都在几乎 1 次调用/秒(脚本试图这样做).如果将顶部的速度变量更改为 20 之类的小值(这意味着它将尝试每秒运行 50 次),则间隔永远不会达到平均每秒 50 次迭代.

In this Fiddle, you can clearly see that the timeout will fall behind, while the interval is almost all the time at almost 1 call/second (which the script is trying to do). If you change the speed variable at the top to something small like 20 (meaning it will try to run 50 times per second), the interval will never quite reach an average of 50 iterations per second.

延迟几乎总是可以忽略不计,但如果您正在编写一些非常精确的程序,您应该选择一个自调整计时器(它本质上是一个基于超时的计时器,它会不断地自我调整它创建的延迟)

The delay is almost always negligible, but if you're programming something really precise, you should go for a self-adjusting timer (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created)

相关文章