Search code examples
javascriptxmlhttprequestpolling

How to update global variable on a successful event from inside a function (polling)?


<script>

var status = {{ check_status }};

call_polling = function() {
    // polling request to API (async)
    success:function(result){
        status = result.check_status;
    }

}


if(status) {
    var timer = setInterval(function() { call_polling(); }, 2000);
}
else{
clearInterval(function(){ call_polling();});
}
</script>

So, I have a code with Async request to see the status of a backend process. So, first I set status to 1 (i.e check_status via context in Django). So, if status is 1 then var timer line will start calling call_polling() function every 2 seconds So, call_polling() will query the API to check the status and on a successful response like {'check_status': 1} it will transfer the status = 1. Indicating the backend process is still running. Once, the backend process is done, I pass the JSON response as {'check_status' : 0} which should be status=0 and then it will not go into if but instead clear the polling Interval (as we know the background processing is already finished) and async call to API Should stop.

But it doesn't works, and the javascript still makes call_polling() to API request every 2 seconds. I figured out the reason as var status is declared globally as 1 and even if I replace status = result.check_status . After the function context it will always remain 1 and go into if loop only; no matter what it receives from JSON response.

So, question is How would I be able to update status and clear the timeout (i.e go to the else part) if result.check_status is 0 (i.e {'check_status':2} as Response from API call) ??


Solution

  • Here's how to do this:

    var status = {{ check_status }};
    
    function call_polling() {
        // polling request to API (async)
        success: function (result){
            status = result.check_status;
            if (status) setTimeout(call_polling, 2000);
        }
    }
    
    call_polling();
    

    In short, as long as the response is 1, a new timeout for the check is set.