문제

Suppose I have a few buttons and when they are clicked they trigger certain setInterval, but when I clicked on different button the previous setInterval doesn't clear or it say it is undefined.

example:

$("#button1").click(function () {

        var url = "xxx";
        var min = "yyy";

        getGraphCredentials3(min,url);

        var onehour = setInterval(function () {
                getGraphCredentials3(min,url);
        }, 5000);


        clearInterval(twohour);  

});


$("#button2").click(function () {

        var url = "zzz";
        var min = "uuu";

        getGraphCredentials3(min,url);

        var twohour = setInterval(function () {
                getGraphCredentials3(min,url);
        }, 5000);


        clearInterval(onehour);      
});

can anyone help please?

much appreciated

도움이 되었습니까?

해결책

The scope of the onehour and twohour functions is the function in which they're declared, so they're not visible from the other callback.

You must declare your variables in a common scope. Do this :

var onehour, twohour;
$("#button1").click(function () {

        var url = "xxx";
        var min = "yyy";

        getGraphCredentials3(min,url);

        onehour = setInterval(function () {
                getGraphCredentials3(min,url);
        }, 5000);


        clearInterval(twohour);  

});


$("#button2").click(function () {

        var url = "zzz";
        var min = "uuu";

        getGraphCredentials3(min,url);

        twohour = setInterval(function () {
                getGraphCredentials3(min,url);
        }, 5000);


        clearInterval(onehour);      
});

다른 팁

Variable onehour and twohour are local to the function. If you declare them globally, it should work fine.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top