-1

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.

  • 2
    That’s not valid JS code, seems to be missing a setTimeout or setInterval … – misorude Jul 17 '19 at 13:44
  • Possible duplicate of [How to stop timer in javascript?](https://stackoverflow.com/questions/49425137/how-to-stop-timer-in-javascript) – misorude Jul 17 '19 at 13:45

2 Answers2

2

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

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()
mplungjan
  • 169,008
  • 28
  • 173
  • 236