Home > Software engineering >  How do i stop a specific function in JavaScript? I dont want the whole program to stop
How do i stop a specific function in JavaScript? I dont want the whole program to stop

Time:06-01

client.on('message', msg => {
  if (msg.content === 'startspam') {
    function spam(){
      msg.channel.send('a')
    }
    setInterval(spam, 2500)
  }
});

client.on('message', msg => {
  if (msg.content === 'stopspam') {
    
  }
});

how to stop the function spam ( sorry I'm new to JavaScript and im trying to learn the basics )

CodePudding user response:

You can use the clearInterval function on the number that setInterval returns to stop the interval. I added some code below to show how that works.

var interval = setInterval(someFuntion, 200);
clearInterval(interval);

CodePudding user response:

Try clearInterval

const print = () => console.log('alive');
const intervalId = setInterval(print, 1000);
const stopInterval = () => clearInterval(intervalId);
<button onclick='stopInterval()'>Stop</button>

CodePudding user response:

Also I would move the statement

function spam(){ 
   msg.channel.send('a') 
} 

outside your current code OR change to an anonymous function:

 tId = setInterval(function() { msg.channel.send('a') }, 2500) 

and have tId as a global variable so you can clearInterval(tId) to stop it

CodePudding user response:

If I understand correctly, you are trying to stop span function that is called within setInterval. This can be done by using clearInterval.

Try this:

client.on('message', msg => {
  var interval;

  function spam(){
      msg.channel.send('a');
  }  

  function start() {
    interval = setInterval(spam, 2500);
  }
  
  function stop() {
     clearInterval(interval);
  }

  if (msg.content === 'startspam') {
    start();
  }
  if (msg.content === 'stopspam') {
    stop();
  }

});

CodePudding user response:

first of all java and javascript are not the same..

and for your question -

you can use this clearInterval().

this function receives the id of the interval you want to stop. and the interval Function returns a unique number so it can used as ID..

the way you do it is somthing like this :

var intervalID = '';

function startInterVal() {
  intervalID = setInterval(() => {
    console.log('Hello')
  }, 1000)
}

function stopInterval() {
  clearInterval(intervalID);
}
<button onClick="startInterVal()">Start</button>

<button onClick="stopInterval()">Stop</button>

hope i helped you :)

  • Related