0

index.ts

if(audio.paused) {
    audio.play()

    audio.addEventListener('timeupdate', (e) => handleAudioPlayer(<HTMLAudioElement>e.target, 
        <HTMLDivElement>audio.parentElement), true);
}

else {
    audio.pause()

    audio.removeEventListener('timeupdate', () => handleAudioPlayer, true);
}

Basically I have a handleAudioPlayer function that takes 2 arguments, when the audio is playing the event listener is added, and when its paused it should get removed, but here the eventListeners are getting duplicated which is bad, any help is appreciated!

Lun
  • 861
  • 1
  • 10
  • 18
  • It is not possible to remove `anonymous` functions. – MrDeibl Oct 20 '21 at 19:12
  • See https://stackoverflow.com/questions/5660131/how-to-removeeventlistener-that-is-addeventlistener-with-anonymous-function – Jay Buckman Oct 20 '21 at 19:13
  • Does this answer your question? [removeEventListener on anonymous functions in JavaScript](https://stackoverflow.com/questions/4950115/removeeventlistener-on-anonymous-functions-in-javascript) – FZs Oct 20 '21 at 19:13

2 Answers2

0

You're trying to remove a different function than you added in the first place. Instead, try to add and remove the same handler.

const handler = (e) => handleAudioPlayer(<HTMLAudioElement>e.target, 
        <HTMLDivElement>audio.parentElement)
audio.addEventListener('timeupdate', handler, true)
audio.removeEventListener('timeupdate', handler, true)
Chris Farmer
  • 24,974
  • 34
  • 121
  • 164
0

In your case you should declare your function to a variable. Then you can remove the eventListener.

if(audio.paused) {
  audio.play()

  audio.addEventListener('timeupdate', handleAudioPlayer, true);
}

else {
  audio.pause()

  audio.removeEventListener('timeupdate', handleAudioPlayer, true);
}

let handleAudioPlayer = (evt) => {
 // do something
};
MrDeibl
  • 157
  • 1
  • 10