简体   繁体   中英

Repeated Ajax calls using SetTimeout javascript, unexpected execution

I list of users in a html table that is dynamically created on page load. Each row has an inline button and each button has onclick="functionName(userId)", calls the following functions:On click show the bootstrap model pop up and then after starts calling ajax. The problem is stopping the ajax calls after user has closed model,and if user clicks on another row/user pass the current userId. for some reason, sometimes ajax calls stop and sometimes dont. Previous userId is also being saved somewhere which is resulting double or triple calls in a given interval. Thank you for your insights. //This function gets called from each row passing its userId:

var timer = null;
function RTLS(id) {
     $('#RTLSModal').modal('show');
    window.clearTimeout(timer);  

    $('#RTLSModal').on('hidden.bs.modal',
        function() {
            window.clearTimeout(timer);
            timer = 0;
            $('#RTLSModal .modal-body').html("");
            $('#RTLSModal').data('bs.modal', null);
        });
    $('#RTLSModal').on('shown.bs.modal',
        function () {
            GetRealTimeScans(id);     

        });
}

function GetRealTimeScans(id) {
    var html = '';
    $.ajax({
        url: '/api/v1/computers/GetRealTimeKeys?computerId=' + id,
        typr: "GET",

        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        success: function (scans) {
            if (scans.length > 0) {
                $.each(scans,
                    function (index, value) {

                        //create html

                    });

                $('#RTLSModal .modal-body').html(html);
            } else {
                html += '<div class=""><h3 style="text-align: center;">No one around</h3></div>';
                $('#RTLSModal .modal-body').html(html);
            }
        },
        complete: function () {
            timer = setTimeout('GetRealTimeScans('+id+')', 10000);
        }
    });
}

So abort the Ajax call so it stops

var timer = null;
var ajaxCall;

function cleanUp () {
  if (timer) window.clearTimeout(timer);
  if (ajaxCall) ajaxCall.abort()
}

and when you make the call

cleanUp()
ajaxCall = $.ajax({})
              .done( function () {
                ajaxCall = null
                timer = window.setTimeout(function(){}, 10000)
              });

And when you bind the events to the modal, you need to remove the previous event handler.

$('#RTLSModal')
  .off('hidden.bs.modal shown.bs.modal')
  .on('hidden.bs.modal', function() {})
  .on('shown.bs.modal', function() {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM