"Unfortunately, it seems that eventListener cannot be removed in JavaScript. (ts

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);
}

My code in index.ts includes a function called handleAudioPlayer with two arguments. When the audio is playing, an event listener is added. And when it's paused, the event listener should be removed. However, I am encountering an issue where the event listeners are getting duplicated, which is causing some problems. Any assistance on how to resolve this would be greatly appreciated!

Answer №1

When modifying event handlers, make sure you are adding and removing the same function rather than a different one. This ensures consistency in your code.

const customHandler = (e) => handleAudioPlayer(<HTMLAudioElement>e.target, 
        <HTMLDivElement>audio.parentElement)
audio.addEventListener('timeupdate', customHandler, true)
audio.removeEventListener('timeupdate', customHandler, true)

Answer №2

To address your situation, it is recommended that you assign your function to a variable. This will enable you to eliminate the eventListener.

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

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

else {
  audio.pause()

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

let manageAudioPlayer = (evt) => {
 // perform certain actions
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Utilizing Dynamic Dropdown Options Pulled from Database and Automatically Refreshing List upon

I am facing a dilemma with displaying dropdown menus for Provinces and Cities, both of which have values coming from the database. While I can easily list the values for Provinces by querying all of them, my issue arises when it comes to displaying Cities. ...

There are no conflicts causing any issues with other jquery libraries

Several days ago, I reached out for assistance in understanding how to implement a no conflict solution. Thanks to @tdanielcox for guiding me through it. I successfully integrated the solution, but it appears to be causing problems with a lightbox that was ...

Display a div when a radio button is selected

For my current project, I am developing a website that includes 2 radio buttons. When the 'Yes' radio button is checked, a specific div should be displayed on the same page immediately. However, if the 'No' radio button is checked, noth ...

Is Ajax still a popular choice for developing web applications?

Currently, I am developing a comprehensive ajax-based web application and have been investigating various frameworks for SEO optimization and history tracking. During my research, I came across an interesting framework at Although it seems promising, I no ...

Conceal and reveal submenu options

I have been exploring a jQuery function that toggles between hiding and showing different divs when a menu item is clicked. However, I am facing an issue where clicking on the same menu item does not close the newly opened div as intended. Additionally, I ...

Adjust columns sizes on ExtJS 6 dashboards in real-time

Is it possible to adjust the column widths within an Ext.dashboard.Dashboard once it has been displayed? The initial configuration sets the column widths as follows: columnWidths: [ 0.35, 0.40, 0.25 ] I would like to dynamically modify them ...

Using AngularJS to retrieve data with an $http request by its unique

I am currently using AngularJS version 1.6.3 My objective is to retrieve data by id, however, I am facing issues on the AngularJS side. On the server side : app.get("/user/:id", function(req,res){ testDb.findOne({_id : req.params.id}, function(err, ...

What is the origin of the libraries found in npm-shrinkwrap that do not match the packages listed in package.json?

I'm puzzled by the presence of `express` in my `npm-shrinkwrap` file as a main dependency. Despite this, `express` is not listed as a dependency in my `package.json` file. I can't find any usage of it in my project. It's not included a ...

Creating custom ExpectedConditions with Protractor for detecting attribute changes

I've been working on creating a custom ExpectedConditions method that can wait for an element attribute to change. Here is the approach I came up with: const CustomExpectedCondition = function() { /** * Check if element's attribute matches ...

An interface designed for enums containing nested types

My task involves creating an interface for the state using an enum as a key and object as a value. How can I designate the enum as the key type? export enum Language { CS, EN } const [userInput, setUserInput] = useState<IUserInput>({ [Lan ...

What is preventing me from adding any style to this specific element?

Currently, I am in the process of creating a stopwatch for solving Rubik's cube. Within this project, there is a div element named "records" that is meant to display the time after a button is clicked. However, I am facing an issue where I am unable t ...

Use Cypress to retrieve a token from an API, store it in local storage, and then use it in the header of another API request. Once the token is successfully incorporated, capture and return the

There is an API (referred to as getToken) that generates a token in its response body. This token is then called and stored in the header of another API (known as returnBody). It seems logical to utilize localStorage for the getToken API since the token ca ...

Turn off the ability to select months in PrimeNG Calendar using Typescript

In my Angular 7 project, I am utilizing PrimeNG Calendar and I am looking to disable the month navigator at the component level based on certain conditions. For example, if the current month is February, I want to disable the month navigator after March. ...

Is it possible to search against objects within an array using search filters in Vue JS?

Currently, my search filter allows users to search for a wine by name and producer location. I would like to enhance this feature to also include searching within a list of objects in an array (grapes). Is this feasible and how can it be implemented? Pleas ...

Retrieving a numerical value from a constantly changing string

The string is constantly changing. For example: Date15:Month8:Year1990 Is there a way to extract the number 15 without using substring, since the values are always different? I am looking to extract only the number after "Date" and before ":". ...

Implementing Dynamic FormControl Values within FormGroup in Angular: A Step-by-Step Guide

GenerateFields(customControl, customValue): FormGroup { return this.fb.group({ customControl: new FormControl(customValue), }) } I am looking for a way to dynamically add the value of customControl from the parameter passed in the Ge ...

Looking for a way to detect changes in a select menu using Angular?

How can I determine with the openedChange event if there have been any changes to the select box items when the mat select panel is closed or opened? Currently, I am only able to detect if the panel is open or closed. I would like to be able to detect any ...

Challenges arise when attempting to break down an API into separate components rather than consolidating it into a

I've been struggling with this issue for a few days now. Problem Explanation: I am trying to use Axios to fetch data and store it in the state for each individual Pokémon. However, currently all the data is being rendered inside a single component w ...

A particular individual experiencing difficulties executing a script within an HTML form that relies on google.script.run.function()

I've developed an input form that operates within an HTML modal launched from a Google Apps Script in a Google Sheet. This form retrieves values from the sheet, allows users to edit or manipulate them, and then writes the changes back into the sheet u ...

Discovering the complete URL utilized to load the application

I am working on an Angular application and I am looking to retrieve the full URL of the application from within the code - specifically, the complete address that the user entered into their browser to access the app. When using Router or ActivatedRoute i ...