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

查看:127
本文介绍了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);

使用 setTimeout setInterval

推荐答案

他们基本上尝试做同样的事情,但 setInterval 方法将比 setTimeout 方法更准确,因为 setTimeout 等待1000ms,运行该函数然后设置另一个超时。所以等待时间实际上超过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 每1000ms执行完全,重要的是要注意 setInterval 也会延迟,因为JavaScript不是多线程语言,这意味着 - 如果脚本的其他部分正在运行 - 间隔必须等待它完成。

Altough 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.

In 这个小提琴,你可以清楚地看到超时将落后,而间隔几乎是所有时间几乎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天全站免登陆