【问题标题】:Javascript setInterval statusJavascript setInterval 状态
【发布时间】:2012-12-29 01:28:00
【问题描述】:

如果我正在编写包含大量间隔的 javascript,我倾向于在间隔对象数组中跟踪它们

function Interval(id, desc){
 this.id = id;
 this.desc = desc;
}

prototypes etc....

然后我用类似的东西创建我的区间函数

intervalArray.push(new Interval(setInterval(function, milli),"Demo interval"))   

我知道这已接近强迫症,但相信我,它使问题解决变得更加容易,因为当您想在运行时清除其中一两个的间隔时,在开发工具提示符处跟踪可悲的事情更简单。

所以问题...

给定一个区间 id,有没有办法访问它的当前状态?

即,如果我将间隔 x 设置为 300000 的重复时间以每五分钟触发一次,有没有办法获得 x.timer,一个在一分钟后返回 60000 的函数?

现在有几次,在调试时,知道给定时间间隔有多接近触发会很有用。

我想我可以向我的间隔对象添加另一个值 - .lastFired,用 0 启动它,并在它触发时用时间戳更新它,但大概浏览器会在某处跟踪间隔......

【问题讨论】:

标签: javascript setinterval


【解决方案1】:

您可以进一步扩展您的区间函数:

function Interval(fn, desc, ms){
  this.desc = desc;
  this.status = -1;

  var that = this;

  this.id = window.setInterval(function () {

    // save some progess to the Interval object
    // that is used, because in interval callback this === window
    that.status++;

    // now call your function fn, using this === Interval object
    fn.call(that);
  }, ms);

  this.stop = function () {
    if (this.id) {
      window.clearInterval(this.id);
      this.id = 0;
      this.status = -1;
    }
  };
}

// Usage:
var myInterval = new Interval(function () {
  // frequent action

  // this === Interval object instance
  if (this.status === 5) this.stop();
}, "description", 10000);

现在您还可以创建一个 onprogress 事件处理程序,例如回调,以便在您的进度发生变化时得到通知。您也可以将this.id = window.setInterval(... 语句移动到this.start = function () { 公共函数中,以便稍后启动和停止。

【讨论】:

  • 我喜欢这样,因为我很少在没有 JQuery 的情况下做任何事情,所以我觉得一个插件即将推出......谢谢
  • @PerryW 不客气。实际上我没有准确回答您的问题,但是我希望您可以为每个 Interval 实例存储一些数据。
【解决方案2】:

浏览器安排回调在间隔到期时运行。在其内部事件循环的每个“滴答”中,它都会检查是否有任何间隔已过期。如果是,则调用其回调。浏览器如何跟踪时间间隔的确切方式取决于实现,但没有显示在调用回调之前它将等待多长时间。所以没有:(

【讨论】:

  • 很害怕所以我要去玩@metadings的建议
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-03
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 2021-08-17
  • 1970-01-01
  • 2019-04-01
相关资源
最近更新 更多