How to stop a for loop inside a function with a button?

Viewed 59

I want my program to generate a random number and multiply it with a number that a user inputs. Then take the result and multiply that with the user inputted number. This part works but how do I stop the loop with a button?

The loop is inside of a function and I want to use a button to stop the for loop. I used setTimeout to delay each result by 1.5 seconds. I tried to use set Interval on the function start but that didn't seem to work.

2 Answers

Here is an example using a recursive setTimeout pattern. It's not very pretty but should be enough for you to work on:

var stopLoop = false;

function start(i) {
  stopLoop = false;
  loop(i);
}

function stop() {
  stopLoop = true;
}

function loop(i) {
  if (stopLoop) {
    stopLoop = false;
  } else {
    setTimeout(function() {
      doWork(i);
    });
  }
}

function doWork(i) {
  document.getElementById("display").innerHTML = i++;
  loop(i);
}
<button onclick="start(0);">
Start Loop
</button>

<button onclick="stop();">
Stop Loop
</button>

<div id="display"></div>

If I understand correctly what you want, then replace setTimeout with setInterval add a button to delete the interval

<script>
    var random = Math.floor(Math.random()*89)+10;
    var i;
    var timer;
        
    function stop() {
        clearInterval(timer)
    }

    function start() {
        var input = document.getElementById("field").value;
        var inputInteger = parseInt(input);
        var total = random * inputInteger;
        var data = total
        var display = document.getElementById("display");
        display.innerHTML = random + " * " + inputInteger + " = " + total + "<br>";
        timer = setInterval(function() {
            var answer = data * inputInteger;
            display.innerHTML += data + " *" + inputInteger + " = " + answer + "<br>";
            data = answer;
            }, 1500);
    }

</script>


<button onclick='start()'>starts</button>

<button onclick='stop()'>stop</button>
Related