Calling onclick start and onclick stop

I use the following functions to start and stop spin.Basically I try to add an Autospin button and tried to approach the approach, but its not working. The start function works, but stops working.

var nIntervId;
this._onAutoSpin = function(){
  s_oGame.onSpin();
  nIntervId = setInterval(this._onAutoSpin, 10 * 1000);
};

this._offAutoSpin = function(){
  clearInterval(nIntervId);
};
+4
source share
2 answers

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); // modified for demo
  }

  this._doAutoSpin = function() {
    console.log('spinning...');
  };

  this._offAutoSpin = function() {
    console.log('stopped');
    clearInterval(nIntervId);
  };
}

var foo = new Foo();
foo._onAutoSpin();

setTimeout(foo._offAutoSpin, 5000); // stop after 5 seconds
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); // modified for demo
  }

  this._offAutoSpin = function() {
    console.log('stopped');
    clearInterval(nIntervId);
  };
}

var foo = new Foo();
foo._onAutoSpin();

setTimeout(foo._offAutoSpin, 5000); // stop after 5 seconds
Hide result
+2

setTimeout setInterval, setInterval .

var nIntervId;
this._onAutoSpin = function(){
  s_oGame.onSpin();
  nIntervId = setTimeout(this._onAutoSpin, 10 * 1000);
};

this._offAutoSpin = function(){
  clearTimeout(nIntervId);
};
0

Source: https://habr.com/ru/post/1675888/


All Articles