简体   繁体   中英

How do I stop this loop with some onclick call function button?

I have here a button to start the function. As usual

<button onclick="start()">START</button>

This is my fuction for my loop.

function start() {
               $.ajax({
                    url: url + value,
                    type: 'GET',
                    async: true,
                    success: function(result) {
                        if (result.match("success")) {
                            removeline();
                            live(result);
                        }else {
                            removeline();
                            dead(result);
                        }
                    }
                });
            }, 2000 * index);
}

Now what function can I use to make the execution of the code stop above to stop. I want something like I can start and stop.

This will likely help

var stopped = false, tId;

function stop() {
  stopped = true;
  clearTimeout(tId);
}

function start() {
  stopped = false;
  $.ajax({
    url: url + value,
    type: 'GET',
    async: true,
    success: function(result) {
      if (result.match("success")) {
        removeline();
        live(result);
      } else {
        removeline();
        dead(result);
      }
      if (!stopped) tId = setTimeout(start, 2000 * index)
    }
  });
}
<button type="button" onclick="start()">START</button>
<button type="button" onclick="stop()">Stop</button>

Try kill the request as shown in Abort Ajax requests using jQuery

var xhr = $.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
     alert( "Data Saved: " + msg );
  }
});
xhr.abort()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM