1

自分自身を再帰的に呼び出すメソッドを持つ 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() の 2 番目の形式を使用して、メソッド自体への参照を渡しました。しかし、それは機能しません。

4

3 に答える 3

9

これを試して:-

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
}
于 2008-12-10T11:55:39.133 に答える
1

最初に言うことは、setTimeout を呼び出しているが間隔を変更していない場合は、setInterval を使用する必要があるということです。

編集(コメントから更新):クラスとして使用され、setInterval/clearIntervalが再参照を必要としない場合、クロージャーからの参照を保持できます。

edit2: calle eを書いたことが指摘されていますが、これはかなり正しく、100% 明確に動作します。

完全を期すために、これは機能します:

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

f();

そのため、alert の代わりに document.write を試しましたが、それが問題のようです。doc.write は書き込みのために DOM を開いたり閉じたりするため、このような問題を抱えています。

于 2008-12-10T11:42:13.890 に答える
0

あなたはそれに向かってポインタを保持することができます...

/* ... */
var func = arguments.callee;
this._updateUITimerHandler = window.setTimeout(function() { func(); }, 1000);
/* ... */
于 2008-12-10T11:55:10.417 に答える