How do I write a recursive method in JavaScript using window.setTimeout ()?

I am writing a JavaSCript class that has a method that calls itself recursively.

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

      

Property Description:

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

      

My problem is that I am using recursion with setTimeout (). I know that setTimeout () will accept any string to execute or a function reference. since this function is a method of an object, I don't know how to call it from outside. so I used the second format setTimeout () and passed a reference to the method itself. but it doesn't work.

+1


source to share


3 answers


Try this: -



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
}

      

+9


source


Well, the first thing to say is that if you call setTimeout but don't change the interval, you must use setInterval.

edit (update from comment): You can keep the link from the closure if it is used as a class and setInterval / clearInterval does not need to be re-referenced.

edit2: it was pointed out that you wrote a review that will work perfectly correctly and 100% unambiguously.



Out of completeness, this works:

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

f();

      

so i tried document.write instead of warning and here is what is the problem. doc.write is fraught with problems like this due to opening and closing the DOM for writing, so maybe you need to change the innerHTML of your target and not doc.write

+1


source


You can hold your pointer to it ...

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

      

0


source







All Articles