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?
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>
You DO need the setTimeout, but it does not have to be 1 sec
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>