由于您被限制为 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,到那个毫秒数,我们都将死去。
为了让你能够设置LongTimeout,你可以修改函数以接受通过引用传递的对象,从而将范围保留回调用函数:
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);