title: Looping audio with Javascript
body: <p>For my audio project I need to create a looping function. for this example the looping time is from 3 seconds to 8 seconds. </p>
  
  <p><strong>What I expect</strong></p>
  
  <p>On clicking on the <code>loop-icon</code> before the 8 second mark I'd expect the audio to begin looping indefinitely once the 8 second mark is passed.</p>
  
  <p>On clicking the <code>loop-icon</code> after the 8 second mark the audio should immediately loop indefinitely between 3 and 8 seconds.</p>
  
  <p>On clicking the <code>loop-icon</code> a second time the looping stops and the audio continues playing as usual. </p>
  
  <p><strong>What is happening</strong></p>
  
  <p>On clicking on the <code>loop-icon</code> before the 8 second mark the audio keeps playing as usual with no loop ever being executed after the 8 second mark is passed. </p>
  
  <p>On clicking on the <code>loop-icon</code> after the 8 second mark causes the loop but only once and the audio plays as usual without ever looping a second time.</p>
  
  <p>On clicking the <code>loop-icon</code> a second time does the same as the above problems.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const audio = document.querySelector('.audio');
  const loopIcon = document.querySelector('.loop-icon');
  
  let loopOn = false;
  
  loopIcon.addEventListener('click', function() {
  
    if (loopOn === false) {
      loopOn = true;
      audio.addEventListener('timeupdate', timeLoop());
    } else {
      loopOn = false;
      audio.removeEventListener('timeupdate', timeLoop());
    }
  });
  
  function timeLoop() {
    if (audio.currentTime &gt;= 8) {
      audio.currentTime = 3;
    }
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;head&gt;
    &lt;link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous"&gt;
  &lt;/head&gt;
  
  &lt;i class="fas fa-redo-alt loop-icon"&gt;&lt;/i&gt;
  &lt;audio class="audio" src="https://radio.pastemagazine.com/audio/320/2146615065.mp3" controls&gt;
  &lt;/audio&gt;</code></pre>
  </div>
  </div>
  </p>