'Remove event listener from the inside if specified callback function

I have a situation, where I want to attach a function with parameters to an event listener, like this:

var pauseAudioAt = function(aud, seconds, removeListener) {
    console.log(aud.currentTime);
    // check whether we have passed 5 minutes,
    // current time is given in seconds
    if(aud.currentTime >= seconds) {
        // pause the playback
        aud.pause();
        if (removeListener) {
            aud.removeEventListener('timeupdate', pauseAudioAt);
            showBtn();
        }
    }

}
audio.addEventListener("timeupdate", function() {
                pauseAudioAt(audio, 18, true);
            });

I want to remove the listener as soon as the function invoked? How can I achieve this ?

Thanks.



Solution 1:[1]

You can only remove exactly the same function you've added

in your case you could do

// added this
var x = function() {
    pauseAudioAt(audio, 18, true);
}
//
var pauseAudioAt = function(aud, seconds, removeListener) {
    console.log(aud.currentTime);
    // check whether we have passed 5 minutes,
    // current time is given in seconds
    if(aud.currentTime >= seconds) {
        // pause the playback
        aud.pause();
        if (removeListener) {
            aud.removeEventListener('timeupdate', x); // changed this
            showBtn();
        }
    }

}
audio.addEventListener("timeupdate", x); // changed this

Solution 2:[2]

Just use named function.

var pauseAudioAt = function(aud, seconds, removeListener) {
    console.log(aud.currentTime);
    // check whether we have passed 5 minutes,
    // current time is given in seconds
    if(aud.currentTime >= seconds) {
        // pause the playback
        aud.pause();
        if (removeListener) {
            aud.removeEventListener('timeupdate', onTimeUpdate);
            showBtn();
        }
    }

}

audio.addEventListener("timeupdate", onTimeUpdate);

function onTimeUpdate() {
    pauseAudioAt(audio, 18, true);
}

It'll remove the handle onTimeUpdate for event timeupdate.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jaromanda X
Solution 2 developer033