javascript - 防止 setInterval 函数运行两次

标签 javascript jquery setinterval

我有一个 setInterval 函数,每小秒运行一次。现在,我正在浏览器中探索我的控制台,我发现 setInterval 函数中的函数有时会运行两次。我怎样才能防止运行两次?

这是我的设置间隔:

$('#myclinic_id').change(function(){
    clearInterval(interval);
    lastQueueID = 0;
    $("#boxqueue").empty();
    var selectedClinicID = $(this).val();
    clinicID = selectedClinicID; 
    statusClinic(clinicID, userID);
    show_patients(clinicID, userID);

    if(selectedClinicID != "0" || selectedClinicID != undefined){
    interval = setInterval(function(){
    check_getqueue(clinicID, userID);
    }, 4000);  
    }
});$('#myclinic_id').change(function(){
    clearInterval(interval);
    lastQueueID = 0;
    $("#boxqueue").empty();
    var selectedClinicID = $(this).val();
    clinicID = selectedClinicID; 
    statusClinic(clinicID, userID);
    show_patients(clinicID, userID);

    if(selectedClinicID != "0" || selectedClinicID != undefined){
    interval = setInterval(function(){
    check_getqueue(clinicID, userID);
    }, 4000);  
    }
});

现在,在 check_getqueue 函数中,我还有一个函数,我想阻止它运行两次,这是我出现的问题。这是我在 check_getqueue 函数中的代码,其中 check_getqueue 函数中名为 refresh_afterdel(clinicID, userID); 的函数我不想阻止运行两次。

这是我的 check_getqueue 的完整代码:

function check_getqueue(clinicID, userID) {
var tmpCountQ = [];
  $.ajax({
    url: siteurl+"sec_myclinic/checkingUpdates/"+clinicID+"/"+userID,
    type: "POST",
    dataType: "JSON",
    success: function(data) {
      for(var i=0;i<data.length;i++) {
        tmpCountQ.push(data[i]['queue_id']);
      };
      if(typeof lastCon[0] != "undefined")
      {
        for(j=0;j < tmpCountQ.length;j++)
        {
          if(tmpCountQ[j] != lastCon[j])
          {
            refresh_afterdel(clinicID, userID);
            lastCon[j] = tmpCountQ[j];
          } 
        }
      }
      else
      {
       lastCon = tmpCountQ;
      }
      // console.log("lastCon "+lastCon)
      // console.log("tmpCountQ "+tmpCountQ);
    }
  });
}

最佳答案

这取决于您想要如何安排。您的 check_getqueue 函数并不与自身重叠,只是该函数启动一个异步进程然后返回;该过程直到稍后才会完成,有时(显然)在下一次调用 check_getqueue 启动下一个异步过程之前尚未完成。

您的两个基本选择是:

  1. 使用保护变量并在设置该变量时忽略对 check_getqueue 的任何调用:

    var check_getqueue_ignore = false;
    function check_getqueue() {
        if (check_getqueue_ignore) {
            return;
        }
        check_getqueue_ignore = true;
        $.ajax({
            // ...
            complete: function() {
                check_getqueue_ignore = false;
            }
        });
    }
    
  2. 根本不要使用setInterval;相反,让 check_getqueue 仅在上一个异步结果返回后安排下一次调用:

    timer = setTimeout(check_getqueue, 4000);
    // ...
    
    function check_getqueue() {
        $.ajax({
            // ...
            complete: function() {
                timer = setTimeout(check_getqueue, 4000);
            }
        });
    }
    

    如果您想尝试使启动间隔尽可能接近 4000 毫秒,您可以记住 check_getqueue 何时启动,并缩短结果出现所需的时间返回:

    timer = setTimeout(check_getqueue, 4000);
    // ...
    
    function check_getqueue() {
        var started = Date.now();
        $.ajax({
            // ...
            complete: function() {
                timer = setTimeout(check_getqueue, Math.max(0, 4000 - (Date.now() - started)));
            }
        });
    }
    

关于javascript - 防止 setInterval 函数运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43468077/

相关文章:

javascript - chrome setInterval() 对于模糊标签无法正常工作,即使是 1 秒或更长的时间

javascript - 如何根据下拉值过滤/呈现项目?

javascript - Angular 1.6 组件绑定(bind)返回未定义

javascript - 在 jQuery 中检查多选下拉列表 focusout 中是否存在数组中的值

javascript - setInterval 和 css() jQuery

javascript - 试图停止最后一项的 setInterval 循环

javascript - JS数组索引号用字符串替换成值

php - ajax 功能和点击功能在点击时不起作用

javascript - MongoDB 第一次不会返回正确的数据

javascript - jQuery $.data() 函数的 Vanilla 替代品 : any native javascript alternative?