Home > OS >  How to stop a for loop inside a function with a button?
How to stop a for loop inside a function with a button?

Time:09-21

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.

<script>
        var random = Math.floor(Math.random()*89) 10;
        var i;
        
        
        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>";
          
            for (i = 1; i < 1000; i  ) {
             
              setTimeout(function() {
                 var answer = data * inputInteger;
                 display.innerHTML  = data   " *    "   inputInteger   " = "   answer   "<br>";
                 data = answer;
              }, 1500 * i);
            }
        }
            
    </script>

CodePudding user response:

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 loop(i) {
  if(i < 1000000) {
    if (stopLoop == false) {
        setTimeout(function() { iterate(i); });
    } else {
        stopLoop = false;
    }
  }
}

function iterate(i) {
  document.getElementById("display").innerHTML = i;
  i  ;
  loop(i);
}
<button onclick="stopLoop=true;">
Stop Loop
</button>

<button onclick="loop(0);">
Start Loop
</button>

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

CodePudding user response:

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