简体   繁体   中英

Why does console.log run infinite loops until overflow, and document.write not

In javascript, if you have an infinite loop using console.log, it will write everything to the console until it overflows. However, if you do this with document.write, in an infinite loop, it will freeze the page and nothing will load. Does anyone know the reason for this?

example is here

<html>
<head>
    <script type='text/javascript'>
    var x = 0;

    function conslog() {
        var x = 0;
        while (1) {
            console.log(x);
            x++;
        }
    }

    function dowrite() {
        var x = 0;
        while (1) {
            document.write(x);
            x++;
        }
    }
    </script>
</head>
<body>
    <button type='button' onClick='conslog()'>console</button>
    <button type='button' onClick='dowrite()'>write</button>
</body>
</html>

http://shodor.org/~amalani/infinite.html

The view process for logged messages is independent of the script. While the script runs in an infinite loop, at some times the renderer will intercept it and show the queued messages.

In contrast, document.write does write to a buffer that is going to be parsed when the pending parsing-blocking script finished running. Only it doesn't finish…

If you'd use the DOM to append new elements, they would probably output.

The page will repaint when Javascript is not executing, if it's running a loop the page won't repaint because Javascript is still executing. The console may repaint while Javascript is running on the page.

Mostly likely because there are no finite limits on the size of the HTML page, but the console debug log will? I'm guessing your CPU load went up as well whilst the browser effectively did nothing more than process a loop. I'm guessing this is with code that's something of the form while (1) { console.log ("something") }; ?

You've not stated what browser this is with, so you'll probably find different browsers have different behaviours of the console log. Those that implement it as a growing list or ring buffer may also suffer the browser hanging as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM