how to write a recursive method in JavaScript using window.setTimeout ()?


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

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 where I'm using recursion with setTimeout(). I know setTimeout() will accept some string to execute, or a reference to a function. since this function is method of an object, I don't know how to call it from outside. so I used the second format of setTimeout() and passed in a reference to the method itself. but it does not work.

Try this:-

Scheduler.prototype.startTimer = function() {
  var self = this;
  function updateTimer() {
    this._currentTime -= 1000;
    self.hTimer = window.setTimeout(updateTimer, 1000)
  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