Ways to prevent the "RangeError: Maximum call stack size exceeded" error

Currently, I am working on developing a maze generating algorithm known as recursive division. This algorithm is relatively straightforward to comprehend: Step 1 involves dividing the grid/chamber with a vertical line if the height is less than the width, and with a horizontal line if the height exceeds the width. Step 2 requires repeating Step 1 with the sub-chambers created by the lines until a maze is formed (when the width or height equals 1 unit).

However, an issue I am encountering with this algorithm is a RangeError in JavaScript, indicating that the maze creation function is being called excessively (as I am attempting to implement the algorithm using a recursive function). Is there any possible solution to avoid or prevent this error? Or is there a critical element missing from my code causing the algorithm to malfunction?

I have experimented with incorporating a trampoline function, yet due to my beginner status, I have struggled with fully grasping it to implement it effectively. Additionally, I have restarted my project approximately three times in the hopes of devising an alternate solution to this problem, but I consistently encounter the same error.

Below is a snippet of my code:

//leftCord = the furthest left x coordinate of my chamber/grid, upCord = the highest y coordinate of my grid, and so on.

//(0, 0) IS LOCATED AT THE UPPER LEFT NODE OF MY GRID

function createMaze(leftCord, rightCord, upCord, downCord) {
var height = Math.abs(downCord - upCord);
var width = Math.abs(rightCord - leftCord);

if (height < 2 || width < 2) {
    //The maze is finished!
    return;
} else {

    if (height < width) {
        //cut the chamber/grid vertically

        //Obtaining an even random number and plotting the function x = 'random number' on the grid
        var x = randomNum(leftCord / 2, rightCord / 2) * 2;

        var lineX = [];
        for (i = upCord; i < downCord; i++) {
            lineX.push(grid[i][x]);
        }

        //Creating a random door/passage ensuring it's odd
        var randomDoor = randomNum(0, lineX.length / 2) * 2 + 1;
        lineX.splice(randomDoor, 1);

        //Drawing the line
        for (i = 0; i < lineX.length; i++) {
            lineX[i].className = "wall";
        }

        //Repeating the process for the left and right sub-chambers created by the line
        createMaze(leftCord, x, upCord, downCord);
        createMaze(x, rightCord, upCord, downCord);

    } else {
        //cut the chamber/grid horizontally

        //Obtaining an even random number and plotting the function y = 'random number' on the grid
        var y = randomNum(0, downCord / 2) * 2;

        var lineY = [];
        for (i = leftCord; i < rightCord; i++) {
            lineY.push(grid[y][i]);
        }

        //Creating a random door/passage ensuring it's odd
        var randomDoor = randomNum(0, lineY.length / 2) * 2 + 1;
        lineY.splice(randomDoor, 1);

        //Drawing the line
        for(i = 0; i < lineY.length; i++){
            lineY[i].className = "wall";
        }

        //Repeating the process for the upper and lower-chambers created by the line
        createMaze(leftCord, rightCord, upCord, y);
        createMaze(leftCord, rightCord, y, downCord);
    }

}

}

Answer №1

The reason behind this issue is that you forget to initialize the variable i with var. As a result, it is being sent into the global scope and gets overwritten with each function call.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting latitude and longitude from Google Maps in a React Native appHere are the steps to

Looking to retrieve the latitude and longitude from Google using React Native. As a newcomer to React Native, I have been unable to find any resources to address this issue. Any assistance would be greatly appreciated. Thanks! Thanks ...

Updating an array using `setState` does not result in the array being updated

I created a component that uses the .map() method to render an array of students and has a button to shuffle and update the display. However, I'm facing an issue where the display does not update every time I click the button. const Home: NextPage = ...

Is it possible to validate an email domain using node.js? For example, checking if gmail.com is a valid email domain, and ensuring that users do not enter incorrect variations such as egmail.com

I've been working with React.js and Express.js/Node.js, utilizing nodemailer for sending emails. However, I've noticed that a lot of emails are coming in with incorrect domains, such as [email protected], rather than the correct ones like [e ...

What is the best way to handle waiting for a JavaScript __doPostBack call in Selenium and WebDriver?

I am encountering a unique issue while automating with Selenium/Python and trying to input data into two fields on a website. The script fills out the first field, ORIGIN CITY, without any problems. I have used WebDriverWait for the second field, DELIVERY ...

ag-grid Server Side pagination function to enable independent setting of last row

Currently, I am utilizing ag-grid, Angular 7, and implementing a server-side datasource with pagination. In my API setup, I initiate two requests: the first request provides the total number of items in the table, while the second fetches the data for the ...

Cloning a checkbox using Jquery

I am working on a search page that utilizes checkboxes to display results. After the user selects certain options and triggers a reload of the page, I want to provide an easy way for them to remove their selections by displaying them at the top of the page ...

Minimize unnecessary rendering in React when toggling between tabs

I am currently working on a React application that utilizes material-ui to generate tabs. <div className={classes.root}> <AppBar position="static"> <Tabs value={value} onChange={handleChange}> <Tab label="Item One" /> ...

Is there a way to seamlessly update button values in VueJs from an api request without needing to reload the page or manually clicking something? Or perhaps there is an alternative method to achieve this?

I attempted to solve the issue by implementing while(true) within the created method so that it constantly updates by sending frequent requests to Flask. Is there a different approach to updating my value? Vue: let app = Vue.createApp({ data ...

What is the best way to manage a promise in Jest?

I am encountering an issue at this particular section of my code. The error message reads: Received promise resolved instead of rejected. I'm uncertain about how to address this problem, could someone provide assistance? it("should not create a m ...

Is it possible for jQuery to detect if an email was sent from the client's email account?

I am working towards a feature on my website where users fill out specific fields and then click "send email" to activate their email platform via "mailTo", with the email pre-populated for easy sending. The challenge lies in confirming if the user actuall ...

How can you create an accordion menu that expands when a button is clicked?

Is there a way to make an accordion menu open when the 'More' button is clicked? I've tried, but it always starts in its expanded state and collapses when the button is clicked. What I really want is for the accordion to be closed initially ...

Incorporate JSON information into a sleek Bootstrap modal interface

I am looking to load a JSON file to generate a list within a Bootstrap Modal. The setup I have allows for the modal to appear when clicking on a person's image. <li class="project span3" data-type="pfa"> <a data-toggle="modal" data-targe ...

Tips for choosing an image using jQuery from an external HTML page

I'm attempting to embed an HTML page within a div and then individually select all the img tags within that page to display an overlay div on top of the images. Currently, I can insert the HTML into a div named "asd" and it seems like the jQuery is f ...

How can I transform this in JavaScript so that it returns a Promise?

Currently, I am trying to implement code that I found in a SaaS's example. The goal is to retrieve the correct URL for a specific action. The sample code provided by the SaaS looks like this, but I would like to modify it so that it returns a Promise ...

Fetching a JSON object from an external URL using JavaScript

Currently, I am working on a project using JavaScript and have an API that provides me with a JSON Object. You can access this JSON object by clicking on the following link: . Within this JSON object, there is a specific element located at JSONOBJECT.posi ...

Is it possible to switch out all instances of "GET" methods with "POST" throughout the codebase?

While working on a web application, we encountered caching issues with Internet Explorer (caching occurred due to the use of GET requests). The problem was resolved when users turned on "Always refresh from server" in IE's Developers Tool. Although we ...

Performance of obtaining image data

Is anyone else experiencing a significant lag when trying to retrieve the state of a single pixel on the canvas? Take a look at my JS code below: var state = ctx.getImageData(x,y,1,1).data; state = 'rgba(' + state[0] + ',' + state[1] ...

"Disabling Click Event on Sidebar Menu in Angular: A Step-by-Step Guide

I am working on an Angular project with a sidebar that I want to modify in order to disable click events on the menu items. My goal is to guide users through a specific flow without allowing them to navigate freely. However, simply disabling the [routerLin ...

The "add to cart" button is unresponsive

My issue is that the add to cart button on my website is not responding properly. I have implemented JavaScript on the add to cart button, where I have assigned an attribute called data-product with a value of {{product.id}}. var updateBtns = document.g ...

Error: The property value supplied for the calc() function is invalid

<App> includes both <Header> and <Content> components. I am attempting to calculate the height of <Content>, which is equal to the height of <App> minus the height of the header. // App.js import { useStyles } from "./Ap ...