javascript - Remove event listener from the inside if specified callback function -


i have situation, want attach function parameters event listener, this:

var pauseaudioat = function(aud, seconds, removelistener) {     console.log(aud.currenttime);     // check whether have passed 5 minutes,     // current time given in seconds     if(aud.currenttime >= seconds) {         // pause playback         aud.pause();         if (removelistener) {             aud.removeeventlistener('timeupdate', pauseaudioat);             showbtn();         }     }  } audio.addeventlistener("timeupdate", function() {                 pauseaudioat(audio, 18, true);             }); 

i want remove listener function invoked? how can achieve ?

thanks.

you have pass .removeeventlistener() reference same function passed .addeventlistener(). 1 way minimal change existing code name (currently anonymous) function expression, pass function pauseaudioat() instead of passing boolean:

var pauseaudioat = function(aud, seconds, listenertoremove) {     console.log(aud.currenttime);     // check whether have passed 5 minutes,     // current time given in seconds     if(aud.currenttime >= seconds) {         // pause playback         aud.pause();         if (typeof listenertoremove === "function") {             aud.removeeventlistener('timeupdate', listenertoremove);             showbtn();         }     }     }  audio.addeventlistener("timeupdate", function listener1() {     pauseaudioat(audio, 18, listener1); }); 

that way, pauseaudioat() doesn't need hardcoded reference function needs removed.

if want call pauseaudioat() without removing listener omit argument: pauseaudioat(audio, 18) - or pass false or null or if that's more convenient: pauseaudioat(audio, 18, null).

(if want able call pauseaudioat() other part of code and remove listener combine function declaration shown in jaromanda x's answer.)


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -