I have base class Timer and a couple of methods inside it. My idea is simple, I need a basic class to run the timer. A lot of various timers as the instances of base class. But I have no idea how should I pass method as a parameter inside the .startTimer and .run
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();
}
}
});
};
When I try to run my crap like this:
var t = new Timer(10000);
t.startTimer(t.ajaxCall("/123", "POST", test2, null));
function test2(resp) {
console.log(resp + '!');
}
it runs only once and stops. How can I fix it?