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

177
Visualizações
Javascript/HTML show alert before value changed on browser

I have a simple counter webpage which has a "+1" button and a count display. When you click the button, the counts on the webpage increases by 1. When the counts reach 5, the page is supposed to pop up an alert and reset the counter to 0.

However, when the counter reaches 5, the webpage still shows "Counts:4" and the alert shows up. What's more, the tag's innerText has already become "Counts:5". So why is there an inconsistence between the HTML and the actual webpage? Does it have anything to do with asynchronous operations?

enter image description here I could add a setTimeout(function(){alert("Counter value: "+ totalCount)},1000); to delay the alert. But that's not my original intention. The alert should always pop up right after the counter hits 5 and displays as "Counts:5".

let totalCount = 0;

function onload() {
  document.getElementById("increment").addEventListener("click", onClick);
  renderCounter();
}

function onClick() {
  totalCount++;
  renderCounter();

  if (totalCount > 4) {
    alert("Counter value: " + totalCount);
    totalCount = 0;
    renderCounter();
  }
}

function renderCounter() {
  let counts = document.getElementById("counter");
  counts.innerText = "Counts: " + totalCount;
}
<body onload="onload()">
  <header id="header">
    <h1>Interesting tests</h1>
  </header>
  <section class="my-counter">
    <p id="counter"></p>
  </section>

  <section id="increment-button">
    <button type="button" id="increment"> +1 </button>
  </section>

  <script src="increment.js"></script>

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

0

You DO need the setTimeout, but it does not have to be 1 sec

  1. Don't reset before rendering
  2. alert is blocking so the interface does not get a chance to update
  3. Allow the rendering, then alert, then render again
  4. Use eventListener instead of inline event handlers

let totalCount = 0;

window.addEventListener("load", function() {
  document.getElementById("increment").addEventListener("click", onClick);
  renderCounter();
})

function onClick() {
  totalCount++;
  renderCounter();
  if (totalCount > 4) {
    totalCount = 0;
    setTimeout(function() {
      alert("Counter value: " + totalCount);
      renderCounter();
    }, 10); // allow the interface to update
  }
}

function renderCounter() {
  let counts = document.getElementById("counter");
  counts.innerText = "Counts: " + totalCount;
}
<header id="header">
  <h1>Interesting tests</h1>
</header>
<section class="my-counter">
  <p id="counter"></p>
</section>

<section id="increment-button">
  <button type="button" id="increment"> +1 </button>
</section>

<script src="increment.js"></script>

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