【问题标题】:how to write a recursive method in JavaScript using window.setTimeout()?如何使用 window.setTimeout() 在 JavaScript 中编写递归方法?
【发布时间】:2010-09-26 05:27:40
【问题描述】:

我正在编写一个 JavaSCript 类,它有一个递归调用自身的方法。

Scheduler.prototype.updateTimer = function () {
    document.write( this._currentTime );
    this._currentTime -= 1000;
    // recursively calls itself
    this._updateUITimerHandler = window.setTimeout( arguments.callee , 1000 );
}

属性描述:

_currentTime: the currentTime of the timer in miliseconds.
_updateUITimerHandler: stores the reference so can be used later with clearTimeout().

我的问题是我在 setTimeout() 中使用递归。我知道 setTimeout() 将接受一些要执行的字符串,或对函数的引用。由于这个函数是一个对象的方法,我不知道如何从外部调用它。所以我使用了 setTimeout() 的第二种格式,并传入了对方法本身的引用。但它不起作用。

【问题讨论】:

  • 这不是递归的,只是连续的

标签: javascript recursion


【解决方案1】:

试试这个:-

Scheduler.prototype.startTimer = function() {
  var self = this;
  function updateTimer() {
    this._currentTime -= 1000;
    self.hTimer = window.setTimeout(updateTimer, 1000)
    self.tick()
  }
  this.hTimer = window.setTimeout(updateTimer, 1000)
}
Scheduler.prototype.stopTimer = function() {
    if (this.hTimer != null) window.clearTimeout(this.hTimer)
  this.hTimer = null;
}
Scheduler.prototype.tick = function() {
  //Do stuff on timer update
}

【讨论】:

  • +1 -- @farzad:我认为这也值得你投赞成票(不仅仅是你的“接受”勾号)。 ;-)
【解决方案2】:

首先要说的是,如果您调用 setTimeout 但不更改间隔,则应该使用 setInterval。

编辑(从评论更新):如果用作类并且 setInterval/clearInterval 不需要重新引用,则可以保留闭包中的引用。

edit2:有人指出您编写了 callee,它将完全正确且 100% 明确地工作。

出于完整性考虑,这是可行的:

function f() 
{
  alert('foo');
  window.setTimeout(arguments.callee,5000);
}

f();

所以我尝试了 document.write 而不是 alert,这似乎是问题所在。 doc.write 充满了这样的问题,因为打开和关闭 DOM 进行写入,所以也许您需要更改目标的 innerHTML 而不是 doc.write

【讨论】:

  • 感谢您的建议。使用 setInterval() 是一个更好的选择。虽然因为我把这个类写成一个库,但我不知道从我的类中实例化的对象的名称。所以我不能在我自己的班级里打电话给他们。
  • 你不是把 callee 和 caller 搞混了吗?
  • ha - 我是对的,callee 工作得很好,会修改
【解决方案3】:

你可以拿着一个指向它的指针...

/* ... */
var func = arguments.callee;
this._updateUITimerHandler = window.setTimeout(function() { func(); }, 1000);
/* ... */

【讨论】:

  • 这并不能解决访问适当实例成员的需要。随后的 func() 调用将使“this”指向窗口对象而不是调度程序的特定实例
猜你喜欢
  • 2019-08-31
  • 1970-01-01
  • 2013-10-12
  • 2011-01-15
  • 2016-04-01
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多