Firefox throwing js error in for loop "allocation size overflow"

18,352

Solution 1

Using string concatenation in this manner is usually a bad idea, especially if you don't know the number of iterations you will be doing. Every time you concatenate a string, you will reallocate the memory needed to fit the new string and need to garbage collect the old one (which might not even be done during the loop for performance reasons)

var htmlBuffer = [];
htmlBuffer.push('<select name="pagenum" id="pagenum" style="width:135px" onChange="setPageSearchValue(this.value)">');
for(i=1 ; i<=tot_pages ; i++)
{
        if(i.toString() == document.frmlist.start.value)
        {
            htmlBuffer.push("<option value='"+i+"' 'selected' >"+i+"</option>");
        }
        else
        {
            htmlBuffer.push("<option value='"+i+"'>"+i+"</option>");
        }
}   
htmlBuffer.push('</select>');

htmlC = htmlBuffer.join('\n');

The above will define an array, to which you push each "row" onto. It will dynamically allocate memory needed for the expanding data, and finally, you allocate 1 string for the total amount of data . This is much more efficient. I don't know if this is the actual problem in your case (since we don't know what tot_pages are), but it's never a bad idea to avoid string concatenations in loops anyway.

Solution 2

Adding a note, this error is likely to be thrown when looping using a malformed do..while inside another loop.

For the record the following snippet can throw this error when removing i++, or a bad condition in the while.

["h","e","l","l","o"].forEach(function(e){
    var k = ["w","o","r","l","d"]
    var i = 0
    do 
      k[i] = e+k[i],i++
    while (i < k.length)
    console.log(k)
    })

Share:
18,352

Related videos on Youtube

Rajasekhar
Author by

Rajasekhar

Updated on June 27, 2022

Comments

  • Rajasekhar
    Rajasekhar almost 2 years

    Below is my code

    Same code is working in local server but not in live.

        htmlC = "";
        htmlC += '<select name="pagenum" id="pagenum" style="width:135px" onChange="setPageSearchValue(this.value)">';
        for(i=1 ; i<=tot_pages ; i++)
        {
                if(i.toString() == document.frmlist.start.value)
                {
                    htmlC += "<option value='"+i+"' 'selected' >"+i+"</option>";
                }
                else
                {
                    htmlC += "<option value='"+i+"'>"+i+"</option>";
                }
        }   
        htmlC += '</select>';
    

    I have tried finding infinite loop but no success. Very same code is working in local server.

    • lukkea
      lukkea over 9 years
      where do you set tot_pages and to what value?