当我收到从我的 ajax 帖子返回的数据时,我试图停止我的超时。但是,我取回了数据,它更新了我的 html,但计时器仍在运行。出了什么问题?
function getResponse() {
var i = 0;
var reply = null;
var myTimer;
while (i < 24 && reply == null) {
(function(i) {
myTimer = setTimeout(function() {
$.ajax({
url: '/getResponse',
data: "123456",
type: 'POST',
success: function (data) {
console.log("HERE data2 " + data);
if(data != "" || data != null){
reply = data;
document.getElementById("responseText").innerHTML = reply;
clearTimeout(myTimer);
}
},
error: function (error) {
document.getElementById("responseText").innerHTML = error;
console.log(error);
}
});
}, 5000 * i)
})(i++)
}
最佳答案
在这里,您将在 while 循环的每次迭代中覆盖全局 myTimer
变量。因此,每次您执行 clearTimeout(myTimer)
时,您只是清除当 i
变为 时运行的最后一个 setTimeout 的超时23
而不是在 while 循环的前 22 次迭代中创建的 setTimeout。实际上,您必须在 while 循环中的 IIFE 内声明 myTimer 变量,如下所示,以便为在 while 循环期间创建的所有 23 个 setTimeout 清除超时:
function getResponse() {
var i = 0;
var reply = null;
// var myTimer;
while (i < 24 && reply == null) {
(function(i) {
var myTimer = setTimeout(function() { // Declare myTimer here
$.ajax({
url: '/getResponse',
data: "123456",
type: 'POST',
success: function (data) {
console.log("HERE data2 " + data);
if(data != "" || data != null){
reply = data;
document.getElementById("responseText").innerHTML = reply;
clearTimeout(myTimer);
}
},
error: function (error) {
document.getElementById("responseText").innerHTML = error;
console.log(error);
}
});
}, 5000 * i)
})(i++)
}
关于javascript - 为什么我的 setTimeout 在我清除时不会停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51608677/