JS hangs on a do while loop

后端 未结 6 1520
南旧
南旧 2020-12-20 07:40

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

6条回答
  •  情书的邮戳
    2020-12-20 08:29

    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:

    • Running a long operation in javascript? (example code for your loop)
    • How can I force the browser to redraw while my script is doing some heavy processing?
    • Javascript async loop processing
    • Prevent long running javascript from locking up browser
    • DOM refresh on long running function
    • Best way to iterate over an array without blocking the UI
    • Javascript - how to avoid blocking the browser while doing heavy work?

提交回复
热议问题