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

203
Visualizações
how to remove the even listener after the array is finished

I'm playing with JS but I'm just a beginner. I guess this way works out for me the best. I want to start a dialog as an event listener by creating new divs with elements of the conversation. I also set the timeInteval after the function is called. How can I avoid displaying "the end" numerous times after the button is clicked again.

  <button id="btn">Start the conversation</button>
  const btn = document.querySelector("#btn");
  const container = document.querySelector(".container");

  const dialog = [
  "🧑 Hello",
  "👧 Hi",
  "🧑 You're new here?",
  "👧 Yes.",
  "🧑 Would you like a drink?",
  "👧 Sure.",
  ];

  let i = 0;

  btn.addEventListener("click", generateConversation);

  // setTimeout(generateConversation, 1000);

 function generateConversation() {
  let newSay = document.createElement("div");
  newSay.innerText = dialog[i];
  container.appendChild(newSay);
  i++;
  setInterval(generateConversation, 1000);

  if (i >= dialog.length) {
    newSay.innerText = "The End";
    intervalId = setInterval(generateConversation, 1000);
    clearInterval(intervalId);
  } 

I applied the suggestions by Pedro but the code keeps running. How to stop it when the dialog.length is reached?

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

0

To only run a EventListener one time you can pass an option of "once": true:

btn.addEventListener("click", generateConversation, { once: true });

Since you only want the conversation to start when the button is clicked move setInterval to inside generateConversation and save it to a variable, it returns an id that can be used to delete it:

clearInterval(intervalId);

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>
<body>
  <button id="btn">Start the conversation</button>
  <div class="container"></div>
  <script>
 const btn = document.querySelector("#btn");
  const container = document.querySelector(".container");

  const dialog = [
  "🧑 Hello",
  "👧 Hi",
  "🧑 You're new here?",
  "👧 Yes.",
  "🧑 Would you like a drink?",
  "👧 Sure.",
  ];

  let i = 0;

  btn.addEventListener("click", generateConversation, { once: true });


  function generateConversation() {
  intervalId = setInterval(() => {
    let newSay = document.createElement("div");
    newSay.innerText = dialog[i];
    container.appendChild(newSay);
    i++;
    if (i >= dialog.length) {
      newSay.innerText = "The End";
      clearInterval(intervalId);
    }
  }, 1000);
  }


</script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

You have assing set interval to a variable like this

var myVar = setInterval(generateConversation, 1000);

and then for clear setInterval pass that var in

clearTimeout(myVar);

for start chat on button click, you have to put this line inside the button click event

var myVar = setInterval(generateConversation, 1000);

check the below update code.

 $("#btn").click(function(){
      myVar = setInterval(generateConversation, 1000);
    }); 

here is the working demo hope it's easy to understand how clearInterval is worked.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>
<body>
  <button id="btn">Start the conversation</button>
  <div class="container"></div>
  <script>
 const btn = document.querySelector("#btn");
  const container = document.querySelector(".container");

  const dialog = [
  "🧑 Hello",
  "👧 Hi",
  "🧑 You're new here?",
  "👧 Yes.",
  "🧑 Would you like a drink?",
  "👧 Sure.",
  ];

  let i = 0;

  

  // setTimeout(generateConversation, 1000);
var myVar;

  function generateConversation() {
  let newSay = document.createElement("div");
  newSay.innerText = dialog[i];
  container.appendChild(newSay);
  i++;
  if (i >= dialog.length) {
    newSay.innerText = "The End";
   myStopFunction();
  }
  }
function myStopFunction() {
  clearTimeout(myVar);
}
$(document).ready(function() {
    $("#btn").click(function(){
      myVar = setInterval(generateConversation, 1000);
    }); 
});


</script>
</body>
</html>

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