为什么我清除时setTimeout不停止?

时间:2018-07-31 08:21:23

标签: javascript jquery ajax settimeout

当我从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++)
}

2 个答案:

答案 0 :(得分:1)

这里,您在while循环的每次迭代中都覆盖全局myTimer变量。因此,每次执行clearTimeout(myTimer)时,您只是清除了i变为23时运行的最后一个 setTimeout 的超时,而不是针对在while循环的前22次迭代。实际上,您必须在while循环中的IIFE中声明myTimer变量,如下所示,以便为while循环中创建的所有23个setTimeout清除clearTimeout:

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++)
}

答案 1 :(得分:0)

已清除。但是您一次又一次地调用函数(23次),并且每次您设置新的超时并再次清除它时。