far*_*zad 1 javascript recursion
我正在编写一个JavaSCript类,它有一个递归调用自身的方法.
Scheduler.prototype.updateTimer = function () {
document.write( this._currentTime );
this._currentTime -= 1000;
// recursively calls itself
this._updateUITimerHandler = window.setTimeout( arguments.callee , 1000 );
}
Run Code Online (Sandbox Code Playgroud)
楼盘简介:
_currentTime: the currentTime of the timer in miliseconds.
_updateUITimerHandler: stores the reference so can be used later with clearTimeout().
Run Code Online (Sandbox Code Playgroud)
我的问题是我在使用setTimeout()的递归.我知道setTimeout()将接受一些要执行的字符串,或者对函数的引用.因为这个函数是一个对象的方法,所以我不知道如何从外面调用它.所以我使用了setTimeout()的第二种格式,并传入了对方法本身的引用.但它不起作用.
试试这个:-
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
}
Run Code Online (Sandbox Code Playgroud)