Question

I've got a script that will generate a map but as it is now, the browser thinks it is running an infinite loop. I know that it will run for possibly quite a long time but it shouldn't affect the browser.

Is there a way to tell the browser to continue the function regardless? Whenever I run it in the browser console I always get "RangeError: Maximum call stack size exceeded".

My function:

function generateMap() {
    map = [];
    for (i1 = 0; i1 < size; i1++) {
        s = '';
        for (i2 = 0; i2 < size; i2++) {
            var r = getRandomInt(1,oneIn);
            if (r == oneIn) s += '1';
            else s += '0';
        }
        map.push(s);
    }
    if (!mapValid(map)) {
        generateMap();
    } else {
        writeToPage(map, 'map');
    }
}

The mapValid() function is rather big so I won't post it here but the entire script including the mapValid() function can be found http://jsfiddle.net/GrV8r/

Was it helpful?

Solution

Aaron recommended breaking, which is one option.

Another option is to use setTimeout to generate a map, then if that fails, generate another.

Using the setTimeout you can make sure it doesn't block the browser.

function generateMap() {
    map = [];
    for (i1 = 0; i1 < size; i1++) {
        s = '';
        for (i2 = 0; i2 < size; i2++) {
            var r = getRandomInt(1,oneIn);
            if (r == oneIn) s += '1';
            else s += '0';
        }
        map.push(s);
    }
    if (!mapValid(map)) {
        console.log("Generating another map.");
        // Note: There is no () after generateMap.  We are passing the function reference.
        window.setTimeout(generateMap, 25);

    } else {
        writeToPage(map, 'map');
    }
}

OTHER TIPS

Your problem is that mapValid(map) doesn't return true for thousands of maps.

That means the recursive approach doesn't work here. Use a loop instead:

while(true) {
   ... generate map ...
   if(mapValid(map)) break;
}

This approach won't exhaust the stack. For safety reasons, you should abort the loop, though so it doesn't block the browser for too long:

for(var guard=0; guard<10000; guard++) {
   ... generate map ...
   if(mapValid(map)) {
       writeToPage(map, 'map');
       return;
   }
}

...unable to generate a valid map...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top