javascript 以负延迟调用 setTimeout 好吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8430966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is calling setTimeout with a negative delay ok?
提问by ripper234
The following snippet sets a timeout that I'd like to last at least a second:
以下代码段设置了我希望至少持续一秒钟的超时:
var currentTimeMillis = new Date().getTime();
// do stuff...
var sleepTime = 1000 - (new Date().getTime() - currentTimeMillis);
Given that sleepTime
can be a negative number, is it safe to call setTimeout
, like this:
鉴于它sleepTime
可能是一个负数,这样调用是否安全setTimeout
:
setTimeout(callback, sleepTime)
Or do I need to check for negative values before calling setTimeout
?
或者我需要在调用之前检查负值setTimeout
吗?
回答by Jonathon Bolster
According to the MDNreference, the specification requires that there is a minimum timeout.
根据MDN参考,规范要求有一个最小超时时间。
If you provide something less than this (HTML5 spec says 4ms) then the browser will just ignore your delay and use the minimum.
如果您提供的内容少于此值(HTML5 规范说 4 毫秒),那么浏览器将忽略您的延迟并使用最小值。
So negatives should be fine, since it'll just be less than the minimum.
所以底片应该没问题,因为它会小于最小值。
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/):
显然,情况并非总是如此(Web 开发不总是这样!)。根据(http://programming.aiham.net/tag/browser-compatibility/):
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.
为 setTimeout 提供负时间并不总是会导致回调函数被调用。这适用于其他浏览器,但在 Internet Explorer(8 或更低版本)中,您必须确保将任何负时间更改为零。
I haven't tested this myself, but like Thomasz said, it's probably better to be safe.
我自己还没有测试过,但就像 Thomasz 说的那样,安全起见可能更好。
回答by Tomasz Nurkiewicz
Better be safe than sorry:
安全总比后悔好:
setTimeout(callback, Math.max(sleepTime, 0))
回答by dku.rajkumar
You could also use a conditional statement, like so:
您还可以使用条件语句,如下所示:
if (sleepTime < 0) {
sleepTime = 0;
}
setTimeout(callback, sleepTime);
回答by Peppe L-G
Hmm... The solutions mentioned solves the problem at the call to setTimeout
, so it needs to be written each time a call is made. Isn't it better to solve it directly in setTimeout
?
嗯... 上面提到的解决方案解决了调用时的问题setTimeout
,所以每次调用时都需要写。直接在里面解决不是更好setTimeout
吗?
// Run this once.
(function(){
var oldSetTimeout = setTimeout
setTimeout = function(callback, delay){
return oldSetTimeout(callback, Math.max(delay, 0))
}
})()
// Call setTimeout safely with a negative delay.
setTimeout(function(){ console.log("Hello World") }, -42)