-2

I want to create a code that loops over an array and prints its index. I have created buttons to Stop (to stop the loop) & Start (to start the loop) the loop.

I have tried to achieve this by creating a condition that checks over a variable stop, If its value is 1 the look should stop, however, this condition doesn't work.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • are you using vanilla js or any of the frameworks like Angulat, React, Vue, etc? – Abhishek Kokate Nov 28 '22 at 06:39
  • 2
    Please read https://stackoverflow.com/help/minimal-reproducible-example we cannot help without seeing relevant code, for example how are you pausing between printing out each number? – A Haworth Nov 28 '22 at 07:01

1 Answers1

0

you can use recursive method and settimeout to set loop time (if needed)

let isStatus = false;
let index = 0;

function myLoop(){
  console.log(index++)
  setTimeout(function() {   
    if(isStatus) {
      myLoop()
    }
  }, 800)
}

function start(){
  index = 0
  isStatus = true;
  myLoop()
}


function pause(){
  isStatus = false;
}


function resume(){
  isStatus = true;
  myLoop()
}
<button onClick="start()">start</button>
<button onClick="pause()">pause/stop</button>
<button onClick="resume()">resume</button>
sikurro
  • 375
  • 2
  • 6
  • 1
    Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. Please _never_ suggest or encourage these attributes. The last browser that still needs them reached end of life nearly two decades ago. – Sebastian Simon Nov 28 '22 at 07:12