0
const target = document.getElementById("button");

function when( event) {
  return new Promise((resolve) => {
    target.addEventListener(event, resolve);
  });
}

when( "click").then(() => {
  alert("button clicked");
});

I dont understand why this event listener function wouldnt go off when you click more than once. Despite being in a promise, the event listener is "registered" to the button. So I feel like it should always go off when clicked.

  • 2
    A promise can only resolve once. The event listener is running every time you click, but calling `resolve()` doesn't do anything after the first time. – Barmar Jul 10 '22 at 02:14
  • 1
    The event listener goes off multiple times. It just doesn't do anything with the promise that is already resolved. – Bergi Jul 10 '22 at 03:53

1 Answers1

1

The function when returns a promise. This promise will resolve(and cause the alert) when event listener calls. Because a promise can only resolve once, the alert only triggers at the first time. After that, you can see console.log('event listener calls') when you click button but the alert would not trigger again.

const target = document.getElementById("button");

function when( event) {
  return new Promise((resolve) => {
    target.addEventListener(event, function() {
      console.log('event listener calls');
      resolve();
    });
  });
}

when( "click").then(() => {
  alert("button clicked");
});
<button id="button">Click Me!</button>
BigLiao
  • 507
  • 3
  • 9