To see the problem in action, see this jsbin. Clicking on the button triggers the buttonHandler()
, which looks like this:
function buttonHandler() {
var elm = document.getElementById("progress");
elm.innerHTML = "thinking";
longPrimeCalc();
}
You would expect that this code changes the text of the div to "thinking", and then runs longPrimeCalc()
, an arithmetic function that takes a few seconds to complete. However, this is not what happens. Instead, "longPrimeCalc" completes first, and then the text is updated to "thinking" after it's done running, as if the order of the two lines of code were reversed.
It appears that the browser does not run "innerHTML" code synchronously, but instead creates a new thread for it that executes at its own leisure.
My questions:
- What is happening under the hood that is leading to this behavior?
- How can I get the browser to behave the way I would expect, that is, force it to update the "innerHTML" before it executes "
longPrimeCalc()
"?
I tested this in the latest version of chrome.