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

146
Visualizações
Run a function only for a set amount of time with Javascript (no jQuery)

I am a newbie.

How do I call a function for a set amount of time, say 3000 milliseconds? I have tried setInterval and setTimeout but they don't work.

if (budgeting === '' || budgeting.indexOf('e') > -1 || budgetValue < 0) {
  let errorHandler = document.createElement('div');
  let textErrorHandler = document.createTextNode('Oops! The balance you entered is invalid. Try again!')
  errorHandler.style.width = '500px';
  errorHandler.style.height = '20px';
  errorHandler.style.background = 'coral';
  errorHandler.style.float = 'left';
  errorHandler.appendChild(textErrorHandler);
  document.body.append(errorHandler);
}

The above is my code currently. What I'm trying to do is display an error message box for 3 seconds(3000 milliseconds), but I want it to only display each time the error occurs, i.e, only once.

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

0

This code can work:

setInterval(() => {console.log("work")}, 3000);
about 4 years ago · Juan Pablo Isaza Relatório

0

When displaying the error, set a timeout to hide it again after an interval. If there's a timeout running when setting the timeout, clear it and set a new one.

The following is a basic implementation. The "Show error" button can be clicked as often as required, it will only show one message, only set one timeout at a time and only linger for the specified interval after the last click:

let showError = (() => {
  let timeoutID;
  return () => {
    let el = document.getElementById('err0');
    el.style.visibility = 'visible';
    // Clear timeout if one might be running
    if (timeoutID) clearTimeout(timeoutID);
    // Set timer for 1,000 ms (1 second), clear timeoutID when finished
    timeoutID = setTimeout(()=>{
      el.style.visibility = 'hidden'; 
      timeoutID = null;
    }, 1000);
  };
})();
#err0 {
  visibility: hidden;
  color: red;
}
<button onclick="showError()">Show error</button>
<span id="err0">Error</span>

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