I have this code http://jsfiddle.net/ee1xuaqs/1/ :
function long_running(status_div) { // does something for 2-3 seconds
var result = 0;
// Use 1000/700/300 limits in Chrome,
// 300/100/100 in IE8, 1000/500/200 in FF
alert('running');
for (var i = 0; i < 1000; i++) {
for (var j = 0; j < 700; j++) {
for (var k = 0; k < 300; k++) {
result = result + i + j + k;
} // end inner
} // end outer for
}
}
$('#do_ok').on('click', function () {
$('#status_ok').text('calculating....');
window.setTimeout(function (){ long_running('#status_ok') }, 1000);
$('#status_ok').text('calclation done');
});
Along with this HTML:
<table border=1>
<tr><td><button id='do_ok'>Do long calc</button></td>
<td><div id='status_ok'>Not Calculating yet.</div></td>
</tr>
</table>
Now, when I click on the button, I get 'calculation done' shown up ('Calculating...' probably flashes for a millisecond or two).
As far as I'm aware, each of these 3 commands inside $('#do_ok').on
creates a separate event, two for updating the DOM and one for setTimeout which completes after 1 second. For the jQuery DOM update commands, the DOM is updated immediately, however, they also create DOM-repaint events which get processed as usual (this is according to this highly voted SO answer). Since I get 3 events, they should be executed in the appropriate order, first 'Calculating..' updating the screen, then long_running
and after all of that, calculation done
.
So why do I get 'calculation done' BEFORE long_running
is executed?