繁体   English   中英

如果延迟超过2147483648毫秒,则setTimeout立即触发

[英]setTimeout fires immediately if the delay more than 2147483648 milliseconds

问题

如果delay超过2147483648毫秒(24.8551天),该功能将立即触发。

setTimeout(function(){ console.log('hey') }, 2147483648) // this fires early
setTimeout(function(){ console.log('hey') }, 2147483647) // this works properly

我在Chrome v26和Node.js v8.21下尝试过它

setTimeout的上限是0x7FFFFFFF (或十进制的2147483647

这是因为setTimeout使用32位整数来存储其延迟值,因此高于此值的任何内容都会导致问题

如果你想要在X天数之后触发的超时,你可以尝试使用setInterval而不是像这样的较低延迟值

function setDaysTimeout(callback,days) {
    // 86400 seconds in a day
    var msInDay = 86400*1000; 

    var dayCount = 0;
    var timer = setInterval(function() {
        dayCount++;  // a day has passed

        if(dayCount == days) {
           clearInterval(timer);
           callback.apply(this,[]);
        }
    },msInDay);
}

然后你会像这样使用它

setDaysTimeout(function() {
     console.log('Four days gone');
},4); // fire after 4 days

由于您被限制为32位,只需将setTimeout包装在递归函数中,如下所示:

function setLongTimeout(callback, timeout_ms)
{

 //if we have to wait more than max time, need to recursively call this function again
 if(timeout_ms > 2147483647)
 {    //now wait until the max wait time passes then call this function again with
      //requested wait - max wait we just did, make sure and pass callback
      setTimeout(function(){ setLongTimeout(callback, (timeout_ms - 2147483647)); },
          2147483647);
 }
 else  //if we are asking to wait less than max, finally just do regular setTimeout and call callback
 {     setTimeout(callback, timeout_ms);     }
}

这不是太复杂,应该可扩展到javascript编号的限制,即1.7976931348623157E + 10308,按这个毫秒数,我们都将死亡并消失。

为了使你能够设置setLongTimeout,你可以修改函数来接受一个通过引用传递的对象,从而将范围保留回调用函数:

function setLongTimeout(callback, timeout_ms, timeoutHandleObject)
{
 //if we have to wait more than max time, need to recursively call this function again
 if(timeout_ms > 2147483647)
 {    //now wait until the max wait time passes then call this function again with
      //requested wait - max wait we just did, make sure and pass callback
      timeoutHandleObject.timeoutHandle = setTimeout(function(){ setLongTimeout(callback, (timeout_ms - 2147483647), timeoutHandleObject); },
          2147483647);
 }
 else  //if we are asking to wait less than max, finally just do regular setTimeout and call callback
 {     timeoutHandleObject.timeoutHandle = setTimeout(callback, timeout_ms);     }
}

现在您可以调用超时,然后在需要时取消它:

var timeoutHandleObject = {};
setLongTimeout(function(){ console.log("Made it!");}, 2147483649, timeoutHandleObject);
setTimeout(function(){ clearTimeout(timeoutHandleObject.timeoutHandle); }, 5000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM