setTimeout 还是 setInterval? [英] setTimeout or setInterval?

查看:33
本文介绍了setTimeout 还是 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);

使用 setTimeoutsetInterval?

推荐答案

他们本质上试图做同样的事情,但是 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.

这个Fiddle中,可以清楚的看到超时会落后,而间隔是几乎所有时间几乎都是 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)

这篇关于setTimeout 还是 setInterval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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