title: Stop and run recursion slider JS
body: <p>I am trying to understand the setTimeout method and recursion.
  I have a simple slidshow based on setTimeout recursion. And I want to stop and run it by clicking on two buttons stop and play. I tried many variants, but don't understand how to clear such recursion timeout and then when I click on play, this slider runs from the slide it was stopped.</p>
  <p>Recursion slider:</p>
  <pre><code>let timer = setTimeout(function slider() {
     
      for (let i = 0; i &lt; images.length; i++) {
          images[i].classList.add('hide');
      }
      currentSlide++;
      if (currentSlide &gt; images.length) {
          currentSlide = 1;
      } 
      images[currentSlide - 1].classList.remove('hide');
      setTimeout(slider, 3000); 
  }, 0);
  </code></pre>
  <p>Buttons:</p>
  <pre><code>stopBtn.addEventListener('click', () =&gt; {
              clearTimeout(timer);
          });
  
  playBtn.addEventListener('click', () =&gt; {
              setTimeout(timer, 3000);
          });
  </code></pre>
  <p>UPD: I've almost achieved the stop/play fuctionality, but when I click on play btn, slideshow continues in 2 slides. And whenever I click on play button the slideshow changes.</p>
  <pre><code>timer = setTimeout(function slider() {
      
      
      for (let i = 0; i &lt; images.length; i++) {
          images[i].classList.add('hide');
      }
      images[currentSlide].classList.remove('hide');
      
      if (currentSlide + 1 === images.length) {
          currentSlide = 0;
          
      } else {
          currentSlide++;
      }
      
      let sllideSwhow = setTimeout(slider, 3000);
      
      stopBtn.addEventListener('click', () =&gt; {
         clearTimeout(sllideSwhow);
      });
      playBtn.addEventListener('click', () =&gt; {
          slider();
      });
      
  }, 0);
  </code></pre>