2

documentation states that clearInterval() is required to be passed in a setIntervalId, therefore the function has to look like:

var logMe = setInterval(function () {...}, interval)

Above function is also being self-invoked as soon as the page loads.

If i try to put it in an anonymous function as below:

var logMe = function (interval) {
    setInterval(function () {
        console.log("whatever");
    }, interval);
};

I can pass an interval argument, but I cannot stop it with:

function stopLogMe() {
    window.clearInterval(logMe);
};

So the question is, can I create a function "setInterval" that I can pass an argument (interval) and also stop it using clearInterval ?

Wesam
  • 932
  • 3
  • 15
  • 27
J. Doe
  • 301
  • 2
  • 13

2 Answers2

2

Define variable and assign timer to it when you're calling logMe function:

var interval = 2000;
var timer = null;

function logMe() {
  timer = setInterval(function() {
    console.log('hello!');
  }, interval);
}

function stopLogMe() {
  window.clearInterval(timer);
}
<button onclick="logMe();">Start</button>
<button onclick="stopLogMe();">Stop</button>
Roland Ruul
  • 1,172
  • 8
  • 15
  • Or an array: `var timer = []; timer.push(setInterval(function() { console.log('hello!'); }, interval))` – mplungjan Oct 08 '18 at 09:23
1

You need to somehow encapsulate the ID and the stop function inside a object or function. The ID must be in local context of the logger so it can access it when it needs to stop. It also allows you to create more then just one logger without making things to complex.

const Interval = function (fn, interval) {
  this.id = setInterval(fn, interval)

  this.clear= function () {
    clearInterval(this.id)
  }
}

// Create new logger
const myLogger = new Interval(function () {
  console.log('Log me')
}, 1000)

// Clear interval after 5 seconds.
setTimeout(myLogger.clear.bind(myLogger), 5000)
Bart
  • 17,070
  • 5
  • 61
  • 80