I have the following JavaScript. The attached code is extremely simplified version of rather complex auto-generated JavaScript that launches the same function on lots of objects (not in loop, but just a bunch of function calls generated).
The problem is that the code is supposed to update an element on each launch of the function. However, that does not happen. Instead, when I press the button it freezes and updates status only after all functions are performed (to "Done"). So why the element is not updated on each call of long_function()
in the following code (and how do I fix that):
<html>
<body>
<h1 id="status">Not yet started</h1>
<button onclick="perform()"> Start! </button>
<script type="text/javascript">
function sleepFor( sleepDuration ){
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
function long_function(number)
{
document.getElementById("status").innerHTML = number;
sleepFor(1000);
}
function perform(number) {
long_function(1);
long_function(2);
document.getElementById("status").innerHTML = "Done";
}
</script>
</body>
</html>
(The problem happens in Google Chrome and Safari)
(Sleep function is taken from answer to What is the JavaScript version of sleep()?)