我有基類Timer和其中的幾個方法。我的想法很簡單,我需要一個基本類來運行計時器。很多不同的定時器都是基類的實例。但我不知道我應該如何傳遞方法作爲參數.startTimer
和.run
在javascript上運行計時器
function Timer(interval) {
this.isTimerRuns = false;
this.timerId = 0;
this.interval = interval;
}
Timer.prototype.run = function (foo) {
if(this.isTimerRuns){
foo();
setTimeout(this.run(foo), this.interval);
}
else{
this.stopTimer();
}
};
Timer.prototype.startTimer = function (foo) {
this.timerId = setTimeout(this.run(foo), this.interval);
this.isTimerRuns = true;
};
Timer.prototype.stopTimer = function() {
clearInterval(this.timerId);
this.isTimerRuns = false;
this.timerId = 0;
};
Timer.prototype.ajaxCall = function (url, method, successFunc, errorFunc) {
$.ajax({
url: url,
type: method,
success: function (data) {
var respond = JSON.parse(data);
successFunc(respond);
},
error: function() {
if(errorFunc != null){
errorFunc();
}
}
});
};
裏面當我嘗試運行我的廢話是這樣的:
var t = new Timer(10000);
t.startTimer(t.ajaxCall("/123", "POST", test2, null));
function test2(resp) {
console.log(resp + '!');
}
它只運行一次,然後停止。我該如何解決它?
這樣做::
看起來像'setTimeout(this.run(foo),this.interval)需要修復... – Teemu
是的。好點。以及run方法不保留超時引用。所以也許整個班級需要一些反思。 –