开发者

Memory leaking recursive javascript functions in IE,FF,GoogleChrome

<html>
    <body>
        <h1 id="t">Initial</h1>
            <script>
                var cnt=0;
                setTimeout("addCounter()",100);
                addCounter=function(){
                    ++cnt;
                    if (cnt>1000000) cnt=0;
                    document.getElementById('t').firstChild.nodeValue='Counter: #'+(cnt开发者_如何学运维);
                    setTimeout("addCounter()",100);
                }
            </script>
    </body>
</html>

When I run this sample code in Internet Explorer/Firefox/Chrome, the memory usage increases until the browser/os runs out of memory and the browser crashes!

Any one can help me to rewrite the code that not wast memory? Or I have report it as a bug for browser developer?


This seems stop the out-of-control memory usage:

<html>
    <body>
        <h1 id="t">Initial</h1>
            <script>
                var cnt=0;
                setTimeout(addCounter,100);
                addCounter=function(){
                    ++cnt;
                    if (cnt>1000000) cnt=0;
                    document.getElementById('t').firstChild.nodeValue='Counter: #'+(cnt);
                    setTimeout(addCounter,100);
                }
            </script>
    </body>
</html>

Don't use setTimeout with a string. It's bad practice for many reasons, and apparently increases memory usage (Disclaimer: I'm no expert on setTimeout).


After I increased memory of test machine, I found that after a while the memory usage did not increase any more! It seem the garbage collector (or any thing that is responsible for real free unused memory) is not optimized for low memory systems (like which one I used im my first tests) In fact Chrome after spending about 50M is ok now, IE 9 after 30M. and I did not check FF yet!


I think browser must have something like memory manager and nicer system and check each process for abandon leak memory and if each script leak any memory, browser must kill script or alarm and then kill it.

  • https://wiki.mozilla.org/Performance/MemShrink

  • https://bugzilla.mozilla.org/show_bug.cgi?id=174359

  • etc ...

ps: this script can use as xss code :D


Remove setTimeout("addCounter()",100); from function body

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜