是否使用负延迟调用setTimeout? [英] Is calling setTimeout with a negative delay ok?

查看:357
本文介绍了是否使用负延迟调用setTimeout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码片段,我希望至少持续一秒钟。所以我这样做:

I have a code snippet that I want to last at least a second. So I do:

var currentTimeMillis = new Date().getTime();
// do stuff
var sleepTime = 1000 - (new Date().getTime() - currentTimeMillis);

请注意,sleepTime可以是负数。我可以吗

Notice that sleepTime can be negative. Can I do

setTimeout(callback, sleepTime)

或者我必须明确检查负值吗?

Or must I check for a negative value explicitly?

推荐答案

根据 MDN 参考,规范要求最小超时。

According to the MDN reference, the specification requires that there is a minimum timeout.

如果你提供的东西少于这个(HTML5规范说4ms),那么浏览器将忽略你的延迟并使用最小值。

If you provide something less than this (HTML5 spec says 4ms) then the browser will just ignore your delay and use the minimum.

所以否定应该没问题,因为它只会低于最低限度。

So negatives should be fine, since it'll just be less than the minimum.

显然,这并不总是case(并不总是与web开发的方式!)。根据( http://programming.aiham.net/tag/browser-compatibility/ ):

Apparently, this isn't always the case (isn't that always the way with web development!). According to ( http://programming.aiham.net/tag/browser-compatibility/ ):


为setTimeout提供负时间并不总是会导致调用
回调函数。这适用于其他浏览器,但在
Internet Explorer(8或更低版本)中,您必须确保任何负
次更改为零。

Providing setTimeout a negative time will not always result in the callback function being called. This works in other browsers, but in Internet Explorer (8 or lower) you have to make sure any negative times are changed to zero.

我自己没有测试过,但是像托马斯说的那样,安全起来可能更好。

I haven't tested this myself, but like Thomasz said, it's probably better to be safe.

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

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