javascriptjqueryajaxjquery-countdown

How to stop AJAX making multiple calls?


I'm using the jquery countdown timer plugin (http://keith-wood.name/countdown.html) to display the time. I'm calling a function to add more time on callback event 'onTick'. When the time countdowns to 00:00:00, the function will make an ajax call to add extra time. It's working fine but every time the timer equals 00, ajax is making multiple calls (>15). How can I make it to send just one call? I tried doing async: false but still it's making multiple calls. Thank you.

$(this).countdown({ until: time, format: 'HMS', onTick: addExtraTime });

function addExtraTime() {      
 if ($.countdown.periodsToSeconds(periods) === 00) {
            var postValue = { ID: id }
            if (!ajaxLoading) {
                ajaxLoading = true;
                $.ajax({
                    url: "@Url.Action("AddExtraTime", "Home")",
                    type: 'post',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(postValue),
                success: function() {
                    // show success
                },
                error: function(data) {
                    // show error
                }
            });
            ajaxLoading = false;
        }
      }
    }

Solution

  • You're setting ajaxLoading = false; even when the ajax request is still being done, set it to false after the request is completed

            if (!ajaxLoading) {
                ajaxLoading = true;
                $.ajax({
                    url: "@Url.Action("AddExtraTime", "Home")",
                    type: 'post',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(postValue),
                success: function() {
                    // show success
                },
                error: function(data) {
                    // show error
                }
                complete: function(){
                     ajaxLoading = false;
                }
            });
            //ajaxLoading = false;
        }