JavaScript getTimeout?

nib*_*bot 17 javascript settimeout

Javascript中的window.setTimeout(和相关的setInterval)函数允许您安排将来某个时间执行的函数:

id = setTimeout(function, delay);
Run Code Online (Sandbox Code Playgroud)

其中"延迟"是您希望调用该函数的未来毫秒数.在此时间过去之前,您可以使用以下命令取消计时器:

clearTimeout(id);
Run Code Online (Sandbox Code Playgroud)

我想要的更新计时器.我希望能够提前或推迟一个定时器,使得该函数被调用x毫秒比原计划.

如果有一个getTimeout方法,你可以这样做:

originally_scheduled_time = getTimeout(id);
updateTimeout(id, originally_schedule_time + new_delay);  // change the time
Run Code Online (Sandbox Code Playgroud)

但据我所知,没有像getTimeout或任何更新现有计时器的方法.

有没有办法访问计划的警报列表并进行修改?

有更好的方法吗?

谢谢!

gna*_*arf 14

如果你真的想要这种功能,你需要自己编写.

您可以为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
Run Code Online (Sandbox Code Playgroud)