The problem is that every time it starts, a new interval starts recursively every time, so you only stop the last timer, not the previous one.
To fix this, change your logic so that there is no possible recursion, and there is only one interval:
function Foo() {
var nIntervId;
this._onAutoSpin = function() {
nIntervId = setInterval(this._doAutoSpin, 1 * 1000);
}
this._doAutoSpin = function() {
console.log('spinning...');
};
this._offAutoSpin = function() {
console.log('stopped');
clearInterval(nIntervId);
};
}
var foo = new Foo();
foo._onAutoSpin();
setTimeout(foo._offAutoSpin, 5000);
Run codeHide result, setTimeout(). this, :
function Foo() {
var nIntervId;
this._onAutoSpin = function() {
var _this = this;
console.log('spinning...');
nIntervId = setTimeout(function() {
_this._onAutoSpin();
}, 1 * 1000);
}
this._offAutoSpin = function() {
console.log('stopped');
clearInterval(nIntervId);
};
}
var foo = new Foo();
foo._onAutoSpin();
setTimeout(foo._offAutoSpin, 5000);
Hide result