Jc *_*ohn 4 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);
}
});
Run Code Online (Sandbox Code Playgroud)
现在,在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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
这取决于您想如何安排。您的check_getqueue函数实际上并不与自身重叠,只是该函数启动一个异步进程然后返回;check_getqueue该过程直到稍后才会完成,有时(显然)在下一次调用启动下一个异步过程之前尚未完成。
您的基本两个选择是:
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;
}
});
}
Run Code Online (Sandbox Code Playgroud)setInterval根本不要使用;相反,check_getqueue仅在上一个异步结果返回后安排下一次调用:
timer = setTimeout(check_getqueue, 4000);
// ...
function check_getqueue() {
$.ajax({
// ...
complete: function() {
timer = setTimeout(check_getqueue, 4000);
}
});
}
Run Code Online (Sandbox Code Playgroud)
如果您想尝试使启动间隔尽可能接近 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)));
}
});
}
Run Code Online (Sandbox Code Playgroud)