For my audio project I need to create a looping function. for this example the looping time is from 3 seconds to 8 seconds.
What I expect
On clicking on the loop-icon
before the 8 second mark I'd expect the audio to begin looping indefinitely once the 8 second mark is passed.
On clicking the loop-icon
after the 8 second mark the audio should immediately loop indefinitely between 3 and 8 seconds.
On clicking the loop-icon
a second time the looping stops and the audio continues playing as usual.
What is happening
On clicking on the loop-icon
before the 8 second mark the audio keeps playing as usual with no loop ever being executed after the 8 second mark is passed.
On clicking on the loop-icon
after the 8 second mark causes the loop but only once and the audio plays as usual without ever looping a second time.
On clicking the loop-icon
a second time does the same as the above problems.
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 >= 8) {
audio.currentTime = 3;
}
}
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
</head>
<i class="fas fa-redo-alt loop-icon"></i>
<audio class="audio" src="https://radio.pastemagazine.com/audio/320/2146615065.mp3" controls>
</audio>