clearInterval 的问题

Trouble with clearInterval

我已经在这里看到很多已解决的问题,但我找不到我的 js 脚本。 我需要使用 setIterval 函数发送数组的每个值,但是在发送最后一个数组的值时我无法停止它。这是代码:

<input type="text" name="urldata" value="">
<button  class="button">SEND</button>


<script type="text/javascript">
    var myArray = ["DW,1,22", "AW,30,2", "DW,1,23", "DW,1,24", "DW,1,25", "DW,0,26"];

$(document).ready(function(){
    var connectionClosed = 1;

    $(".button").click(function(){
        var handle = setInterval(function () {  SEND(connectionClosed, myArray);    }, 300);        
    });


function SEND(){   

console.log("connectionClosed="+connectionClosed);

            if (typeof(myArray[0]) !== "undefined" && connectionClosed == 1) {

            connectionClosed = 0; // waiting for http://192.168.4.1:80/ server connection closed

                $.ajax({
                    method: "GET",
                    url: "http://192.168.4.1:80/",
                    data: { cmd: myArray[0]+"," },
                    complete: function(xhr, statusText){
                        myArray.shift(); //delete first value, ready for next value
                        connectionClosed = 1;
                    }
                }); 
            }
            else {
                stopinterval(handle);
                return false;

            }
}

function stopinterval(){
  clearInterval(handle); 
}

});
    </script>

问题出在变量的范围上。您需要将变量的声明移动到 clearInterval 行可以引用它的地方..

$(document).ready(function(){
  var connectionClosed = 1;
  var handle; //  declare it here

  $(".button").click(function(){
    handle = setInterval(function () {  SEND(connectionClosed, myArray); }, 300);        
  });