Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript setInterval clearInterval Simple Example Not Working Explained?

I have a very simple JS setInterval and clearInterval example that doesn't work. There has got to be an underlying reason why it does not work and I would like to know why that is:

 var automessage;

 function turnON() //executed by onclick event A
 {
   var automessage = setInterval(function(){ something() }, 2000);
 }

 function turnOff() //executed by onclick event B
 {
   clearInterval(automessage);
 }

 function something()
 {
   //pulls instant messages
 }

In this example, an end-user clicks a button to start a timed interval process, clicks another button to stop the timed interval process, and then clicks the on button again to start the process again. Essentially, it would be an on/off styled process.

This doesn't work and I am trying to figure out why. I can make all of the hundreds of other examples offered on Stackoverflow to work, but I really need an on/off styled process that isn't limited to just on, and then off. The setInterval should be able to turn on and off at any time.

I really appreciate anyone's help. Also, I do not use any Jquery libraries.

like image 731
user175328 Avatar asked May 19 '26 00:05

user175328


1 Answers

automessage is declared twice - as a global variable and as a local variable. try:

function turnON() //executed by onclick event A
{
    automessage = setInterval(function(){ something() }, 2000);
}
like image 116
Roy Miloh Avatar answered May 21 '26 13:05

Roy Miloh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!