I have a function that runs speech recognition when I click button start, when speech recognition is over some actions should be started. I use addEventListener('audioend', ()=>...) to track the event. Everything work as expected, but now I am adding another functionality to stop listening when I click the same button and the function should be completed also. But I faced an issue with addEventListener that runs despite the return key word.
const recognition = new SpeechRecognition.getRecognition()
const [isPlaying, setIsPlaying] = useState(false)
function playSong() {
setIsPlaying(!isPlaying) //when I click 'Play' button again it changes to 'Stop'
if (listening) { //verify if speech recognition listening
SpeechRecognition.stopListening()
console.log('Should stop here')
return //I try to use return but it doesn't help, in any case addEventListener runs next
}else if {
recognition.addEventListener('audioend', () => {
console.log('Some other actions')
}
........
}
Instead of return you need to remove the event listener
const dosomeaction = () => {
console.log("do some action")
};
recognition.addEventListener('audioend', dosomeaction)
In this way you add the event listiner so you can remove it by this way
recognition.removeEventListener('audioend', dosomeaction)