Borja
Borja

Reputation: 3559

clearInterval doesn't work if is in click jquery event?

I want to use clearInterval but I don't know why doesn't work.

var orologio_real;  //global variable 

$(document).ready(function(){
    orologio(1);

    $('#change-time').on('click', function(){
        clearInterval(orologio_real);   
        orologio(0);
    });
});

function orologio (arg){
    orologio_real= setInterval(function(){
    alert(arg)
    }, 1000);
}

What I don't understand is why if I click on div, clearInterval doesn't work

Upvotes: 0

Views: 55

Answers (1)

Sandip Ghosh
Sandip Ghosh

Reputation: 719

I think it is a silly mistake. You are setting the time interval all over again inside the click handler. I commented it out, and increased the interval a little so that you get time to click the button

var orologio_real;  //global variable 

$(document).ready(function(){
    orologio(1);

    $('#change-time').on('click', function(){
        clearInterval(orologio_real);   
        //orologio(0); //this was the issue
    });
});

function orologio (arg){
    orologio_real= setInterval(function(){
    console.log(arg);
    alert(arg);
    }, 3000);
}

Upvotes: 1

Related Questions