Javascript setInterval clearInterval Simple Example Not Working Explained?

烂漫一生 提交于 2019-11-29 12:13:13

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);
}
Niccolò Campolungo
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.

change

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

to

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

in turnON()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!