Beweelam
Beweelam

Reputation: 1126

How can user break JS loop with a button

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
});

Upvotes: 1

Views: 245

Answers (1)

Kunal Vohra
Kunal Vohra

Reputation: 2846

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);
};

Upvotes: 2

Related Questions