再次 setTimeout 与 setInterval [英] setTimeout vs setInterval again

查看:46
本文介绍了再次 setTimeout 与 setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道 setTimeoutsetInterval 之间存在差异,但请考虑以下两个代码示例:

So I know that there are differences between setTimeout and setInterval, but consider these two code examples:

function myFunction(){
   setTimeout('myFunction();', 100);
   doSomething();
}
setTimeout('myFunction();', 100);

function myFunction(){
   doSomething();
}
setInterval('myFunction();', 100);

请注意,在第一个示例中,我在函数的开头调用了 setTimeout,然后调用了 doSomething.因此,doSomething() 没有额外的延迟.这是否意味着这两个示例完全相同?还是有更细微的区别?

Note that in the first example I call setTimeout at the begining of the function and then I doSomething. Therefore there is no extra delay from doSomething(). Does that mean that those two examples do exactly the same? Or is there even more subtle difference?

推荐答案

它们在功能上大致相同,但也存在差异.一个区别在于如果 doSomething 花费的时间超过间隔时间,浏览器将如何处理它.使用 setInterval,如果 doSomething 仍在运行,至少有些浏览器会跳过下一个时间间隔.因此,如果您使用 100 毫秒,而 doSomething 需要 110 毫秒来运行,那么下一次运行要等到 90 毫秒后才会发生(当然,所有这些时间都是近似值).

They're functionally about the same, but there are differences. One difference is in how browsers handle it if doSomething takes longer than the interval. With setInterval, at least some browsers will just skip the next interval if doSomething is still running. So if you use 100ms as you have, and doSomething takes 110 ms to run, the next run won't happen until 90ms later (of course, all of these times are approximate).

另一个区别是,使用 setTimeout,你每次都会得到一个新的句柄,而使用 setInterval 你得到一个句柄.

Another difference is that with the setTimeout, you'll get a new handle every time, whereas with setInterval you get one handle.

与您给出的示例的另一个不同之处在于,在 setTimeout 示例中,您每次都会启动一个 JavaScript 解析器/编译器,而 setInterval 你只启动解析器/编译器一次.但是这种差异应该无关紧要,因为您根本不应该这样做 —见下文.

Another difference with your examples as given is that in the setTimeout example, you're firing up a JavaScript parser/compiler every time, whereas with setInterval you're only firing up the parser/compiler once. But this difference shouldn't matter, because you shouldn't be doing that at all — see below.

但撇开微妙之处不谈,您拥有的功能在功能上是相同的.

But subtleties aside, what you have there is functionally the same.

旁注:将字符串传递到 setTimeoutsetInterval 不是最佳做法.相反,传入一个函数引用:

Side note: It's not best practice to pass strings into either setTimeout or setInterval. Instead, pass in a function reference:

// setTimeout
function myFunction(){
   setTimeout(myFunction, 100);
   doSomething();
}
setTimeout(myFunction, 100);

// setInterval
function myFunction(){
   doSomething();
}
setInterval(myFunction, 100);

传入一个字符串会启动一个 JavaScript 解析器,并与 eval 做同样的事情.应该尽可能避免(而且几乎总是可能的).

Passing in a string fires up a JavaScript parser and does the same thing as eval. It should be avoided whenever possible (and it's almost always possible).

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

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