Трабл с clearInterval - PullRequest
       10

Трабл с clearInterval

0 голосов
/ 16 ноября 2018

Я уже много видел разрешенных проблем здесь, но я не могу найти ни одного в своем скрипте 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>

1 Ответ

0 голосов
/ 16 ноября 2018

Проблема связана с областью действия переменной.Вам нужно переместить объявление переменной, где строка clearInterval может ссылаться на нее ..

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

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