Why in the following code I see the whole page at once ? Thanks !
HTML:
<div></div>
CSS:
div {
width: 100px;
height: 300px;
border: 1px solid black;
text-align: center;
}
Javascript:
$(function() {
for (var i=0; i<15; i++) {
sleep(100);
$("div").append("<span>--- " + i + " ---<br /></span>");
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
});
Because Javascript on web browsers is single-threaded (although that’s changing; see below) and virtually no browser updates its UI while the (main) Javascript thread is busy. All your
sleepfunction does is block everything for 100ms, it doesn’t let the browser do anything else like update its UI (e.g., doesn’t “yield”).There are a couple of ways to do what you’re trying to do:
Use the new web workers stuff; but note that it’s not widely-supported yet.
Make your loop a function that calls itself via
setTimeout. That way, your code is yielding to the browser and letting it update its UI.Here’s a simple example of how you might apply #2 above to your code:
If you have a lot of loop iterations (e.g., a couple of hundred instead of 15), it may well be worth doing a chunk of them on each iteration rather than yielding on each iteration; the yield takes a measureable time (typically ~10-15ms).