window.setTimeout Javascript 中的(和相关的 setInterval)函数允许您安排一个函数在未来的某个时间执行:
id = setTimeout(function, delay);
其中“延迟”是您希望调用函数的 future 毫秒数。在此时间过去之前,您可以使用以下方式取消计时器:
clearTimeout(id);
我想要的是更新计时器。我希望能够提前或延迟计时器,以便函数被调用 x 毫秒 早 或 晚 比原计划。
如果有 getTimeout 方法,你可以这样做:
originally_scheduled_time = getTimeout(id);
updateTimeout(id, originally_schedule_time + new_delay); // change the time
但据我所知,没有像 getTimeout 或任何更新现有计时器的方法。
有没有办法访问计划警报列表并修改它们?
有没有更好的方法?
谢谢!
最佳答案
如果您真的想要这种功能,则需要自己编写。
您可以为 setTimeout 调用创建一个包装器,它将返回一个您可以用来“推迟”计时器的对象:
function setAdvancedTimer(f, delay) {
var obj = {
firetime: delay + (+new Date()), // the extra + turns the date into an int
called: false,
canceled: false,
callback: f
};
// this function will set obj.called, and then call the function whenever
// the timeout eventually fires.
var callfunc = function() { obj.called = true; f(); };
// calling .extend(1000) will add 1000ms to the time and reset the timeout.
// also, calling .extend(-1000) will remove 1000ms, setting timer to 0ms if needed
obj.extend = function(ms) {
// break early if it already fired
if (obj.called || obj.canceled) return false;
// clear old timer, calculate new timer
clearTimeout(obj.timeout);
obj.firetime += ms;
var newDelay = obj.firetime - new Date(); // figure out new ms
if (newDelay < 0) newDelay = 0;
obj.timeout = setTimeout(callfunc, newDelay);
return obj;
};
// Cancel the timer...
obj.cancel = function() {
obj.canceled = true;
clearTimeout(obj.timeout);
};
// call the initial timer...
obj.timeout = setTimeout(callfunc, delay);
// return our object with the helper functions....
return obj;
}
var d = +new Date();
var timer = setAdvancedTimer(function() { alert('test'+ (+new Date() - d)); }, 1000);
timer.extend(1000);
// should alert about 2000ms later
关于JavaScript 获取超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1957142/