Javascript setInterval clearInterval Simple Exampl

2020-02-13 03:05发布

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.

3条回答
相关推荐>>
2楼-- · 2020-02-13 03:45
var automessage;

function turnON() { //executed by onclick event A 
    automessage = setInterval(function(){ something() }, 2000);
}
function turnOff() { //executed by onclick event B
    clearInterval(automessage);
}
function something() {
    //pulls instant messages
}

This code should work. Yours isn't working because in the context of the turnON function you are always initializing a new variable called automessage, which obfuscates the global one. By not using var you will be overriding the automessage global variable.

automessage is a global variable, so it is editable from any other script. Since, IMHO, it shouldn't be possible, I'd recommend you to use a closure to encapsulate and make private the automessage variable(something like a modular pattern should help you, see below).

var buttonModule = (function() {
    var _automessage;
    function turnON() { //executed by onclick event A 
        _automessage = setInterval(_something, 2000);
    }
    function turnOFF() { //executed by onclick event B
        clearInterval(_automessage);
    }
    function _something() {
        //pulls instant messages
    }
    return {
        turnON: turnON,
        turnOFF: turnOFF
    };
})();

Then you can use it this way: buttonModule.turnON, buttonModule.turnOFF inside your click handlers.

查看更多
走好不送
3楼-- · 2020-02-13 03:53

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);
}
查看更多
虎瘦雄心在
4楼-- · 2020-02-13 04:06

change

var automessage = setInterval(function(){ something() }, 2000);

to

automessage = setInterval(function(){ something() }, 2000);

in turnON()

查看更多
登录 后发表回答