Pergunta

Hello there: i strike once again with a problem.

I created function that makes button work like, eh, tumbler. But i cant find a way to stop setInterval with clearInterval from another button state.

function goIdle(checker)
{
if(checker===1){
buttonDeeper.disabled=true;
var intIdle=(setInterval(goDeeperTest, 2000));//(600000-(bootTier*600)));
buttonIdle.value='Остановиться';
buttonIdle.addEventListener('click', function() {goIdle(2)}, false);
}
if (checker===2) {
clearInterval(intIdle);
buttonDeeper.disabled = false;
buttonIdle.value='Разбежаться';
buttonIdle.addEventListener('click', function() {goIdle(1)}, false);

}
Foi útil?

Solução

The intIdle variable is local to one execution of your goIdle function. Declare it in the outer scope so that it is kept between function executions :

var intIdle;
function goIdle(checker)
{
if(checker===1){
buttonDeeper.disabled=true;
intIdle=(setInterval(goDeeperTest, 2000));//(600000-(bootTier*600)));
buttonIdle.value='Остановиться';
buttonIdle.addEventListener('click', function() {goIdle(2)}, false);
}
if (checker===2) {
clearInterval(intIdle);
buttonDeeper.disabled = false;
buttonIdle.value='Разбежаться';
buttonIdle.addEventListener('click', function() {goIdle(1)}, false);

}

But Another problem you have is that you never seem to remove the event listeners. So at each click, you call one more of them. It can't work. What you really seem to want is

buttonIdle.addEventListener('click', goIdle, false);
var intIdle;
function goIdle() {
    if (intIdle) {
        clearInterval(intIdle);
        buttonIdle.value='Разбежаться';
        buttonDeeper.disabled = false;
        intIdle = 0;
    } else {
        intIdle=setInterval(goDeeperTest, 2000);
        buttonDeeper.disabled = true;
        buttonIdle.value='Остановиться';
    }
}

Outras dicas

Instead of

buttonIdle.addEventListener('click', function() {goIdle(2)}, false);

use

buttonIdle.onclick = function() {goIdle(2)}, false);

otherwise your button keeps having 2 listeners.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top