user17382064
user17382064

Reputation:

How to prevent function/event from firing multiple times

There is an issue with the createResetHandler function.

The createResetHandler function event fires multiple times.

Seen Here: https://jsfiddle.net/oxjzmk18/

To reproduce, when the exit button appears on the screen, click it multiple times.

Clicking on the exit button multiple times causes the event to be fired multiple times.

You have to mouse click the exit button more than 1 time.

How do I prevent that, so that it only fires 1 time?

How is that fixed in the code?

  function createResetHandler(player) {
    const resetVideo = document.querySelectorAll(".exit");
    resetVideo.forEach(function resetVideoHandler(video) {
      video.addEventListener("click", function resetVideoHandler() {
        player.destroy();
        console.log("createResetHandler");
      });
    })
  }

enter image description here

Upvotes: 1

Views: 2080

Answers (1)

ProDec
ProDec

Reputation: 5410

This could work.

Attach event handler to the active exit button only, document.querySelector could be better choice in this case.

const resetVideo = document.querySelectorAll(".container.active .exit");

attach event with once: true, so event handler is removed once the event is fired.

  function createResetHandler(player) {

    const resetVideo = document.querySelectorAll(".container.active .exit");
    resetVideo.forEach(function resetVideoHandler(video) {
      video.addEventListener("click", function resetVideoHandler() {
        player.destroy();
        console.log("removePlayer");
      }, {
        once: true
      });
    })
  }

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

  • once

A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

Or using removeEventListener

  function createResetHandler(player) {

    const resetVideo = document.querySelectorAll(".container.active .exit");
    resetVideo.forEach(function resetVideoHandler(video) {
      const resetVideoHandler = () => {
         video.removeEventListener("click", resetVideoHandler);
          player.destroy();
          console.log("removePlayer");
      };
      video.addEventListener("click", resetVideoHandler);
    })
  }

Upvotes: 1

Related Questions