Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
Why isnt the event listener going off more than once?
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda