1

How a user can stop a loop by clicking a button

Here what I need to do in my loop :

HTML :

<input type="button" id="stop" value="Stop" />
<input type="button" id="go" value="Go" />
<div id="div"> </div>

Javascript :

document.getElementById('go').addEventListener('click', function(){
    // request to server that return a list of object.

  // for each returned objet, I do another request to the server. like that
  for(let i=0; i < objets.length; i++){
    // request to the server.
    // update the div for progress bar like 1%..2%
  }

});

document.getElementById('stop').addEventListener('click', function(){
    // how to break the loop made by go button
});
Beweelam
  • 870
  • 9
  • 11
  • 1
    Does this answer your question? [Implementing a pause and resume mechanism for javascript loop execution](https://stackoverflow.com/questions/26696717/implementing-a-pause-and-resume-mechanism-for-javascript-loop-execution) – Abdul Basit May 04 '20 at 17:06

1 Answers1

2

If you're running a simple for (..) loop, this cannot be stopped via external influence. Everything is happening on the same thread in Javascript, unless your code "ends" at some point and returns control to the browser for a while no UI interaction can happen. The easiest way to have a "loop" is via a setTimeout or setInterval:

interval = null;

startBTN.onclick = function () {
    var i = 0;
    interval = setInterval(function () {
        console.log(i++);  // this is inside your loop
    }, 1);
};

stopBTN.onclick = function () {
    clearInterval(interval);
};
Kunal Vohra
  • 2,703
  • 2
  • 15
  • 33