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

184
Visualizações
How can I implement a timer using setTimeout and clearTimeout

I iterate over the array of questions/answers in which I used to display.

const data = [
    {
        question: "xxx",
        answer: "xxxx."
    },
    {
        question: "xxx",
        answer: "xxx?"
    },
// etc, etc...

I then create a for loop that creates an article element, button, h3, and paragraph. It will then have text content for each button that says '+' and every time I click on the button, it reveals the answer and when I click back it hides.

I'm looking for a way to implement the setTimout which sets a timer for revealing the answer and then a clearTimeout to cancel once the time is up.

const main = document.querySelector('main');
data.forEach(trivia => {
  const article = document.createElement('article');

  const button = document.createElement('button');
  button.type = 'button';
  button.textContent = '+';
  button.addEventListener('click', () => {
    button.textContent = p.classList.contains('hidden') ? '-' : '+';
    p.classList.toggle('hidden');
  });
  article.appendChild(button);

  const h3 = document.createElement('h3');
  h3.textContent = trivia.question;
  article.appendChild(h3);

  const p = document.createElement('p');
  p.textContent = trivia.answer;
  p.classList.add('hidden');
  article.appendChild(p);

  main.appendChild(article);
});

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

0

Adding setTimeout() on the listener would be a good place in your case.

button.addEventListener('click', () => {
  button.textContent = p.classList.contains('hidden') ? '-' : '+';
  p.classList.toggle('hidden');
  const timer = setTimeout(() => {
    // code for hiding the element
    clearTimeout(timer);
  }, 5000); // 5 seconds
  if (p.classList.contains('hidden')) {
    clearTimeout(timer);
  }
});

Demo:

fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(users => {
    for (const user of users) {
      const section = document.createElement('section');
      const label = document.createElement('label');
      const button = document.createElement('button');
      const paragraph = document.createElement('p');

      label.textContent = user.name;

      button.textContent = '+';
      button.addEventListener('click', (event) => {
        const btn = event.target;
        const p = btn.nextElementSibling;

        switch (p.style.display) {
          case 'block':
            btn.textContent = '+';
            p.style.display = 'none';
            break;
          case 'none':
            btn.textContent = '-';
            p.style.display = 'block';
            break;
        }

        const timer = setTimeout(() => {
          btn.textContent = '+';
          p.style.display = 'none';
          clearTimeout(timer);
        }, 5000);

        if (p.style.display === 'none') {
          clearTimeout(timer);
        }
      });

      paragraph.style.display = 'none';
      paragraph.textContent = JSON.stringify(user.address);

      section.append(label);
      section.append(button);
      section.append(paragraph);
      document.body.append(section);
    }
  })
  .catch(error => {
    console.error(error);
  })
<html>

<body></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