Node.js use setInterval & clearInterval on a function

Viewed 273

Hello is there a way to call a function with setInterval and clear the interval later?

Example: When I write in a chat !start the interval function should start with a interval. And when I write !stop in the chat the function with the interval on it should stop.

This is my function:

function abb(channel){
    console.log('Auto-Ban-Bot Timer running...')
    getChannelViewers(channel.replace('#','')).then(
        promise => {
            var vierwernames = promise.chatters.viewers;
            vierwernames.forEach(element => {
                checkFriendlyBots(element)
            });
        }
    );
}

I've tried many things but only got the !start command working, not the !stop command.

1 Answers

This is exactly what clearInterval() method does. It clears a timer set with the setInterval() method.

Check out this example:

const interval = setInterval(myTimer, 1000);
let i = 0;

function myTimer() {
  console.log(i++);
  if (i === 5){
    stop();
  }
}

function stop() {
  clearInterval(interval);
}

Related