Home » Javascript » JavaScript seInterval/clearInterval

JavaScript seInterval/clearInterval

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have a small problem.
The code is like this:

var myModule = (function() {
var _fun = function() {
  console.log('dummy content');
};

var _init = function() {
  _fun();
};

return {
  init: _init,
}

})();

setInterval(myModule.init, 1000);

Is there any option to clearInterval() right after setInterval() and then start it once again ?
I would like to achieve something like this because each time I seInterval() I should clear it but unfortunately I don’t know how to do this :/

Any suggestions ?

Answers:

Simply assign setInterval return value to a variable and then use clearInterval on it, eg:

var myVar = setInterval(myModule.init, 1000);
clearInterval(myVar);

Questions:
Answers:
var myModule = (function() {
var _fun = function() {
  console.log('dummy content');
};

var _init = function() {
  _fun();
};

return {
  init: _init,
}

})();

var interval = setInterval(myModule.init, 1000); // creates interval
clearInterval(interval); // clears the interval created above

Questions:
Answers:

When you set your interval keep a reference to it:

intervalObj = setInterval(yourCallbackFuction, INTERVAL_Time);

Then clearing it:

 clearInterval(intervalObj);