0
function parseAttach(b)
{
    var h="";
    for(i=0;i<b.length;i++)
    {
        var a=b[i];
        switch(a['type'])
        {
            case "image":
                h+='<li class="attach aImg" style="background:#000;border-bottom:2px solid #fff"><img style="max-width:425px;max-height:500px" src="http://img.xiami.com/u/phoo/'+a['file']+'"></li>';
            break;
            case "video":
                h+='<li class="attach aVideo" style="background:#f3f3f3"><span class="MxND" f="'+a['from']+'" d="'+a['id']+'"></span></li>';
            break;
            case "music":
                h+='<li class="attach aMusic"><embed src="http://www.xiami.com/widget/0_'+a['id']+'/singlePlayer.swf" type="application/x-shockwave-flash" width="257" height="33" wmode="transparent"></embed></li>';
            break;
        }
    }
    return h;
}

Once above function is running, the page cannot be interacted, memory and cpu usage of that page skyrocket.

this is an example of parameter b passed to this function:

[{"type":"video","from":"k6","id":"kyxGTZbD-vQ8Domm-eeHiQ"}]

b.length is not more than 2 and this function was executed no more than three times. If this function is removed, memory leaking will not happen.

UPDATE:

Following @GarethMcCaughan 's suggestion, I added alert(i) to the top of the loop, it keeps alerting 0, I headed to the invocation code:

for(i=0;i<c[0].length;i++)//the breakpoint
{
    ......
    if(t[6].length>0)
    {
        //console.log(t[6].length);
        //var a=parseAttach(t[6]);
        var a="";
        h+='<ul class="attaches">'+a+'</ul>';
    }
   ......
}

as you see in the comment, if I replace the invocation with a console.log, the log only show 4 times of execution. But why the function are invoked repeatedly?

Then I found the console report a breakpoint at the top of the loop(I've comment it out), is this the reason why the function keeps invoking?

4

2 回答 2

0

在您的两个循环中,您都没有放在变量var之前。i这意味着它是全球性的。如果它是全局的,那么两个循环都使用相同 i的.

for(i=0;i<b.length;i++)

添加 var 它应该修复它:

for(var i=0;i<b.length;i++)

编辑:进一步澄清:

for(i=0;i<c[0].length;i++)
{
    ......
    if(t[6].length>0)
    {
        // THIS CALL WILL SET THE GLOBAL i TO t[6].length
        var a=parseAttach(t[6]);
    }
   ......
}

因此,外部循环的退出条件永远不会满足,循环的每次迭代都会i返回,因此i永远不会到达c[0].length

于 2012-05-10T00:37:35.210 回答
0

除了一个错误之外,一切似乎都很好:您忘记将 counter 变量设置为i本地变量。当从循环调用时,代码将重置外部循环的同名计数器变量(为 2,因为这是最大长度)并使其永远不会达到其结束条件:

var i; // this variable will always be referenced
function x(number) {
    for (i=0; i<number; i++)
        dosomething;
}
for (i=0; i<5; i++)
    x(2); // resets i to 2
// => never-ending loop

无限循环将使您的浏览器挂起,冻结界面直到代码执行。某些浏览器可能会因运行时间过长的脚本而引发错误,并通过超时实现。

于 2012-05-10T00:41:27.407 回答