所以我有这个函数来检查对手何时连接。一切正常,除了 clearInterval 的东西......我尝试添加 window.setInterval 和 window.clearInterval 。我尝试添加 self 。也...
$(document).ready(function() {
var waitForOpponent = setInterval(checkUserStatus, 2000);
function checkUserStatus() {
$('#user').load('checkuser.php?randval='+ Math.random());
$("#user").ajaxStop(function(){
if(document.getElementById("user").innerHTML!=""){
clearInterval(waitForOpponent);
opponentConnected();
}
});
}
});
我也尝试过这样:
var waitForOpponent;
function check() { waitForOpponent = setInterval(checkUserStatus, 2000); }
check();
请帮帮我......我尝试了一切......
最佳答案
摆脱ajaxStop
并使用.load
的成功回调。
$('#user').load('checkuser.php?randval='+ Math.random(),function(){
if(document.getElementById("user").innerHTML!=""){
clearInterval(waitForOpponent);
opponentConnected();
}
});
如果请求花费的时间超过 2 秒,ajaxstop 将永远不会被调用。
我认为更好的选择是不使用 setInterval:
function checkUserStatus() {
$('#user').load('checkuser.php?randval='+ Math.random(),function(){
if(document.getElementById("user").innerHTML!=""){
opponentConnected();
return; // exit
}
setTimeout(checkUserStatus,2000); // continue after 2 seconds
});
}
checkUserStatus(); // start it up
这可以防止 ajax 请求在连接速度慢或超时时堆积。
关于javascript - 清除间隔不起作用(尝试了所有其他答案),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15275788/