For a live demonstration of the issue, visit this jsbin. When the button is clicked, it triggers the buttonHandler()
function, which is outlined below:
function buttonHandler() {
var elm = document.getElementById("progress");
elm.innerHTML = "thinking";
longPrimeCalc();
}
The expectation is that this code should update the div text to "thinking" and then initiate the execution of longPrimeCalc()
, a complex arithmetic operation that takes a few seconds to be processed. Surprisingly, the actual behavior observed is different. The "longPrimeCalc" operation completes first before updating the text to "thinking," almost as if the sequence of these two lines in the code has been reversed.
It seems like the browser doesn't handle the "innerHTML" code synchronously; instead, it creates a separate thread for its execution at its own pace.
So, here are my inquiries:
- What exactly is going on behind the scenes that causes this unexpected behavior?
- Is there a way to compel the browser to behave as intended and update the "innerHTML" before proceeding with "
longPrimeCalc()
"?
This test was conducted using the latest version of Google Chrome.