Caelan Grgurovic Caelan Grgurovic - 1 month ago 18
Javascript Question

id constantly being clicked using setinterval

I'm creating an audio web player which I would like to function continuously, meaning that when a piece of audio finishes playing, it moves onto playing the next one.

However, I have come across a problem where everything works as it should, but once the previous audio finishes playing, and the next one starts, every 2 seconds, the new one will play & pause; continuously.

This is my current

JavaScript
code block:

function playPauseButton(button, wave, trackID){
var button = $(button); // play button

if(wave.isPlaying()){ // if the audio is playing and the user clicks play button, pause the audio
button.removeClass("playing");
wave.pause();
} else { // vice versa
button.addClass("playing");
wave.play();
}
waveDuration = wave.getDuration(); // audio duration
var nextTrack = ++trackID; // get the current audio track ID and plus 1 to get the new track ID

setInterval(function(){ // check every 2 seconds if the audio is finished playing
if(wave.getCurrentTime() >= waveDuration){ // if it has, make the play button a pause button
button.removeClass("playing");
$(nextTrack + '-ppbutton').click(); // simulate new track play button click
}
}, 2000);
}


& my very simple
HTML
play button:

<!-- onclick play audio (if paused), pause audio (if playing) !-->
<div onclick="playPauseButton(this, a2wave, 2);" id="2-ppbutton"></div>
<!-- 2 is the id !-->


I've been trying to figure this out for hours, however, it is still confusing me (I'm not that good at JavaScript)

All help & suggestions are appreciated.

I've tried to comment on everything to help you understand

UPDATE:

Thanks to ValLeNain for fixing my issue; really appreciate it! :)

However, if people would still like to make suggestions or edits, you are more than welcome too!

Thanks.

Answer

Every time you click the play/pause button, you call setInterval. So you're likely to have several time-based triggers at the same time and the condition probably keeps being true.

What if you replace your call to setInterval with:

var trigger = setInterval(function(){ // check every 2 seconds if the audio is finished playing
        if(wave.getCurrentTime() >= waveDuration){ // if it has make the play button, a pause button
            button.removeClass("playing");
            $(nextTrack + '-ppbutton').click(); // simulate new track play button click
            clearInterval(trigger);
        }    
    }, 2000);