I am wondering how I can solve a hanging page with JS.
I have a JS loop which I\'m testing like this, but it seems to hang forever - is there a way to stop it hangin
Tight loop is likely to always exhaust computing power. I would do it in chunks. Say, divide your list into smaller lists and pause 5ms in between lists. I can provide an example if you need.
You are concatenating 10,000,000
consecutive numbers together into a string, which really will not work well on any modern supercomputer.
If you'd like to poll the progress, setup a timer to do it somewhat slower. It isn't practical, but it looks nice: http://jsfiddle.net/V6jjT/2/
HTML:
<div id="my_data"></div>
Script:
var value = 0;
var interval = setInterval(function() {
if (value > 100) {
clearInterval(interval);
return;
}
value++;
document.getElementById('my_data').innerHTML += ' ' + value;
}, 10);
You should not update the HTML each iteration.
function test(value){
output= [];
do {
value++;
output.push(value);
} while(value < 10000000);
document.getElementById('my_data').innerHTML = (output.join(''));
alert('end'); // never occurs
}
should work (although 10 million numbers in a HTML will still need their time to render).
If you want to see numbers running, you should have a look at window.setInterval - the browser needs some time between js execution to refresh its view. So, you will have to rewrite your code running several chunks of data asynchrously. See also:
You're updating the DOM with an increasingly long string ten million times.
If you're some sort of super-being from the future, then maybe this makes sense.
Running a tight loop like that will not update anything until it's done; besides, 10M array items?!
If you really want to do this and not let the browser hang until forever you have to use setInterval
to allow the browser to refresh in between.
function updater(value, max, interval) {
var output = [],
node = document.getElementById('my_data'),
tid = setInterval(function() {
if (value++ < max) {
output.push(value);
node.innerHTML = (output.join(''));
} else {
alert('done');
clearInterval(tid);
}
}, interval);
}
updater(0, 10, 200);
Javascript is single-threaded, so nothing else can happen while it's running your loop. It's running ten million times, and on each run it's setting the innerHTML of #my_data to something new. It's very inefficient and seems useless. What are you trying to accomplish?