具有随机重复时间的计时器管理器

TimerManager with random recurTime

本文关键字:计时器 管理器 时间 随机      更新时间:2023-09-26

我想要每次迭代的随机过期时间。此示例将仅随机化 5~15 秒之间的过期时间并永久使用它们。

var timer = qx.util.TimerManager.getInstance();
timer.start(function(userData, timerId)
    {
        this.debug("timer tick");
    },
    (Math.floor(Math.random()*11)*1000) + 5000,
    this,
    null,
    0
);

如果有的话,我也接受纯JS解决方案。

http://demo.qooxdoo.org/current/apiviewer/#qx.util.TimerManager

问题是 TimerManager.start 的 recurTime 参数是普通函数的普通参数,因此在调用函数时只计算一次。这不是一个一遍又一遍地重新计算的表达式。这意味着您只能使用TimerManager获得等距执行。

您可能必须手动编写所需的代码,例如,使用qx.event.Timer.once每次调用重新计算超时。

编辑:

这里有一个代码片段,可能会朝着正确的方向发展(这将在 qooxdoo 类的上下文中工作):

var that = this;
function doStuff(timeout) {
  // do the things here you want to do in every timeout
  // this example just logs the new calculated time offset
  that.debug(timeout);
}
function callBack() {
  // this just calls doStuff and handles a new time offset
  var timeout = (Math.floor(Math.random()*11)*1000) + 5000;
  doStuff(timeout);
  qx.event.Timer.once(callBack, that, timeout);
}
// fire off the first execution
qx.event.Timer.once(callBack, that, 5000);