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

1 Answer 1

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);
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.