如果延迟超过2147483648毫秒,则setTimeout立即触发 [英] setTimeout fires immediately if the delay more than 2147483648 milliseconds

查看:151
本文介绍了如果延迟超过2147483648毫秒,则setTimeout立即触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If the delay is more than 2147483648 milliseconds(24.8551 days) the function will fire immediately.

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

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

I tried it under Chrome v26 and Node.js v8.21

推荐答案

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

The upper limit of setTimeout is 0x7FFFFFFF (or 2147483647 in decimal)

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

This is because setTimeout uses a 32bit integer to store its delay value, so anything above that will cause the problem

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

If you want a timeout which fires after an X ammount of days, you could try to use setInterval instead with a lower delay value like this

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

这篇关于如果延迟超过2147483648毫秒,则setTimeout立即触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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