edit the value of a variable in a for() loop

I'm making a website where there is a counter of your steps. It's a exercice I made for myself since I'm beggining and learning. Every second the script is adding one step until it reaches "steps" (which is 5 for this exemple) I would like the user to be able to click add 100 steps so it doesn't end at 5. I'm doing all this with a for() because it's the easiest way I found to later update things on the page every steps.

The story telling is :

  1. The user sees steps going up, 1, 2, 3, 4, 5
  2. They can click "add 100" to add 100 more steps (so the counter keeps going)
  3. the counter is updated and keeps going until 105 (meaning the first 5 + 100 more they just added)
  4. If they want, they can add 100 extra steps again (they don't have to wait until the counter reaches 105)
  5. and go to 205

It's actually not working and I can't see what is wrong. I nailed to replace steps with the value of 100 and console.log() it to debug a bit. But It's not addind 100 to the previous step value neither updating the for() to keep going until 105.

Thanks for the help

let steps = 5;
$( document ).ready(function() {
  
  $(document).on("click", ".add", function() { 
  let steps =  100; // should be actual steps value + 100
  console.log(steps);
      });     
    for (var i = 0; i < steps; i++) { 
        var nbOfSteps = 0 // the numer of steps actually displayed to the user
        setTimeout(function () {
            nbOfSteps++;
            var addSteps = $("<div />", {"class": "steps"})
            .css({})
            .append($("<p>" + nbOfSteps + " steps </p>"))
            .appendTo(".one")
            $(".steps").prev().remove();
 // do some other things here
        }, 1000 * i) //update i every 1000 milliseconds
    }                 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one" id="gauche"></div>
<div class="add"> add 100 steps</div>

EDIT

So I have been experimenting with


$( document ).ready(function() {
  let foots = 3;
  let i = 0;
while (i < foots) {
  setInterval(function () {
  console.log(i);
  }, 1000)
  i++;
  if (i > foots) {
    console.log("ping")
  }
}
});

as @sirEgghead suggested. But I can't seem to manage do make anything out of it.



Read more here: https://stackoverflow.com/questions/64954806/edit-the-value-of-a-variable-in-a-for-loop

Content Attribution

This content was originally published by pual at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: