Javascript counter to call ajax function

1

I'm starting with JavaScript and Ajax and I need a little help pls. I have two Ajax functions that load HTML to an assigned div, inside there is a second counter that refreshes the Ajax function (it works!) But when I give the button to pass to the other Ajax function I keep the previous counter running and I it refreshes the function of before and the new one (go lioo!) I leave the code to you here

<script>
function loadactivity () {  
    \$.post("http://miweb/ajax.cgi",
        {
        'action': "activity",
        'region': "$region",
        'bracket': "$bracket"
        },
        function(data){
            \$("#activity").html(data);
        }
    );
}
function loadtracking () {  
    \$.post("http://miweb/ajax.cgi",
        {
        'action': "tracking",
        'region': "$region",
        'bracket': "$bracket"
        },
        function(data){
            \$("#activity").html(data);
        }
    );
}
function countdown(action, seconds) {
    if (action == "stop") {
        clearInterval(timerId);
    }
    else {
        var count = seconds;
        var timerId = setInterval(function() {
            count--;
            document.getElementById("countdowntimer").textContent = count;
            if(count == 0) {
                clearInterval(timerId);
                if (action == "activity") {
                    loadactivity();
                }
                if (action == "tracking") {
                    loadtracking();
                }
            }
        }, 1000);
    }
}
loadactivity();
 </script>

In the Ajax functions, the following goes:

<script>
countdown("stop");
countdown("activity", 30);
</script>
    
asked by Akond 26.10.2017 в 04:18
source

1 answer

1

I already got it to work. The problem was in the variable timerId, I could not access it in the if stop pq was not yet declared, but this code stayed with me:

...
var timerId;
function countdown(action, seconds) {
    var count = seconds;
    timerId = setInterval(function() {
        count--;
        document.getElementById("countdowntimer").textContent = count;
        if(count == 0) {
            stopinterval();
            if (action == "activity") {
                loadactivity();
            }
            if (action == "tracking") {
                loadtracking();
            }
        }
    }, 1000);
}
function stopinterval () {
    clearInterval(timerId);
}

and in the functions that Ajax calls

<script>
stopinterval();
countdown("tracking", 60);
</script>
    
answered by 28.10.2017 в 23:31