Ответы пользователя по тегу JavaScript
  • Как остановить цикл по нажатию кнопки html / js?

    @Shavadrius
    <code lang="html">
    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>My Hell looper</h2>
    
    <button type="button" id="stopBtn">STOP THIS!!!</button>
    <p id="counter"></p>
    
    <p id="demo"></p>
    
    <script>
    let counter = 0, keepLooping = true;
    const htmlCounter = document.getElementById("counter");
    const step = () => {
      console.log(counter++);
      htmlCounter.innerHTML = counter;
    }
    
    const loop = () => {
      if (!keepLooping) {
      	htmlCounter.innerHTML = `stopped at ${counter} step by click!`;
      	return;	
      }
        step();
        setTimeout(loop, 1000);
    }
    
    const btn = document.getElementById("stopBtn");
    btn.onclick = function(){
      keepLooping = false;
    }
    /*START HELL*/
    
    loop();
    
    </script>
    </body>
    </html>
    </code>
    Ответ написан
    Комментировать