Rendering text with javascript in a loop - browser goes unresponsive
I have a piece of javascript that loops a number of times calculating stuff and it is supposed to output some text to screen every iteration, but instead it goes away开发者_StackOverflow社区 for a long time and flushes everything at once to screen.
There probably are known tricks to get the thing to iteratively update rather than hanging onto the output then flushing, problem is I don't know them!
Any help appreciated.
UPDATE: I altered my code to use setTimeout as some of you suggested but I am afraid it's not helping. I still I won't see anything till the processing is complete. I also tried increasing the timeout but the effect is still the same (by increasing the timeout between each iteration it obviously takes more time but still the browser goes unresponsive). Any idea?
That sounds like expected behaviour. The JavaScript is probably running faster than the browser can render its output.
It sounds like you want to show a progress list of actions? Perhaps you could have them all on the page, with display: none
and switch them to display: block
may be faster.
Alternatively, if you don't want absolute precision, play with setTimeout()
.
You should assume that while your code is running, the view on the screen will not be updated (and in the worst case, even the browser user interface will be unresponsive). You'll need to split your processing into steps, and let the browser process events once in a while. I don't know what your exact problem is, but here's an example of something that should be close.
var i = 0;
function count() {
i++;
document.getElementsById("log").innerHTML += i + "<br />";
setTimeout(count, 1000);
}
count();
The timeout can be really small. Using a timeout of 0 lets the browser process events and then immediately return to your code. Just remember to let the browser process events often enough so the page remains responsive.
There has been some work lately related to supporting threads in the browser, but that kind of stuff isn't really supported by all the big browsers yet.
setTimeout(), setInterval() are the best ways to implement wait/pause function in javascript. Here is sample program to dispay 10 number with 100 millisecs time interval between each.
<button id="startProgram" onclick="startProgram()">Start</button>
<div id="content"></div>
<script type="text/javascript">
function startProgram() {
var content = document.getElementById("content");
var string = "";
for(var i = 0; i < 10; i++) {
string = string + i + "<br/>";
setTimeout('display("' + string + '")', 100 * i);
}
}
function display(string) {
content.innerHTML = string;
}
</script>
Paste this code into a blank html file to check it.
If you only need to support bleeding-edge browsers, use Web Workers.
精彩评论