-1

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.

bruh18014
  • 1
  • 1
  • 1
    The problem with your approach is that you initially create 1000 timeouts, and you are hoping there is an easy way to remove them once something happens. There isn't. Instead either create the next timeout within the code of the previous one, or consider setInterval. – James Sep 20 '22 at 14:21
  • Why start with the random number? Then incrementally multiply it by the user input? ...curious. – bloodyKnuckles Sep 20 '22 at 14:40

1 Answers1

0

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>
Alfie
  • 2,341
  • 2
  • 28
  • 45