The act of populating a JavaScript array with random numbers is causing the browser to crash

For those who engage in D&D type games, I have created two javascript functions to simulate dice rolls.

The initial function, known as getRandom(), accepts a low number and high number as parameters and then produces a random integer between them.

function getRandom(low, high) {
    return Math.floor(Math.random() * (high - low + 1)) + low;
}

The second function, dropLow(), is designed to roll the dice four times, remove the lowest scoring die, and sum up the remaining three. If the total exceeds 9, it will be returned.

function dropLow() {
    var rolls = [],
        lowest,
        total;
    do {
        total = 0;
        for (x = 0; x < 4; x++) {
            rolls.push(getRandom(1,6));
            total += rolls[x];
        }
        lowest = rolls[0];
        for (x = 1; x < 4; x++) {
            if (rolls[x] < lowest) {
                lowest = rolls[x];
            }
        }
        total -= lowest;
    } while (total < 10);
    rolls.length = 0;
    return total;
}

While calling dropLow() once seems to work fine initially, multiple calls start causing my browser (Chrome) to crash with the error message: "Aw Snap! Something went wrong while displaying this webpage." The issue persists even when trying different browsers or devices.

I've explored options like destroying or clearing out the array's contents to prevent continuous building on the original data, but the problem remains unresolved.

If anyone has insights on why or how this is happening, I would greatly appreciate your help!

Answer №1

Make sure to relocate the statement rolls = [] within the do loop.

Without resetting the array, the code is constantly referencing old values. This can result in a crash if the do..while loop iterates more than once with the same values stored, leading to an unexpected halt in the program's execution.

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

How to use hooks in NETXJS to pass data from a page to a component

Hey there, how are you doing? I am currently working on a project using Next.js and styled components. I am trying to change a string using props in my layout component, where the main content is dynamic per page. Page 'prueba.js' import React f ...

I am getting zero results when trying to retrieve data from the users table in Parse Server

Using Parse Cloud to update user information, the user is in the database but querying the users table returns nothing. There is a desire to update a field and save it back. Below is the cloud function being used: Parse.Cloud.define("update", async(reques ...

WebLogic 11g deployment causing a jQuery error stating "Property or method not supported by object."

While deploying my application in WebLogic 9.2, I encountered a JavaScript error stating "Object doesn't support this property or method." Despite the error, the functionality on button click was still working. However, when deploying the same applica ...

The mysterious problem of an undefined event in the Revealing Pattern in JavaScript

Struggling with my use of the modular design pattern for JS and encountering issues with arguments bound functions. I have a function that I want to bind to different events to avoid repetitively writing it out for each event. The only difference in the fu ...

Use jQuery to insert the current date into an input field, but do so only if the field is currently

I am looking to automatically add the current day and month to input fields only if they are empty. If the fields already have data, I do not want them to change. Here's the concept: I have two fields, one for the month and one for the day. If the in ...

Issue with Material UI styles not applied in component (alert: multiple occurrences of `@material-ui/styles`)

I have developed a standalone React component that utilizes the Material UI (4.8.3) library and have uploaded it to a private NPM package for use across various applications. The standalone component project is functioning properly (tested using Storybook ...

The specified container does not exist in the DOM: MERN

I am currently working on a project where I aim to develop a Web Application featuring a stock dashboard. During my coding process, I encountered a minor issue that can be seen in this image. My goal is to have a login form displayed on the browser using ...

Reset preview image upon submission

I have a contact form where I am using the following code to display an uploaded image preview: [file fileuploader filetypes:jpg id:uploader] <img id="preview" src="#" /> <script> var uploader = document.getElementById(&apos ...

How to switch between different ng-class styles

Within this ng-repeat loop, I intend to display the first two rows. Upon clicking "Show More," how can I switch the CSS from display:block to something else? The Show More button should toggle the visibility. JSON "one":[{ "name":"Raspberry Lemo ...

Increase the visibility of a div using Jquery and decrease its visibility with the "

Can anyone assist me with implementing a "show more" and "show less" feature for a specific div? I have put together a DEMO on codepen.io In the DEMO, there are 8 red-framed div elements. I am looking to display a "show more" link if the total number of ...

Evaluating the highest value within a continuous stream of data using idiomatic RxJS methods

When it comes to calculating the maximum value of a fixed stream, the process is quite simple. For example: var source = Rx.Observable.from([1,3,5,7,9,2,4,6,8]).max(); However, this only outputs a single value (9 in this case). What I aim to achieve is ...

Approach to dividing PHP output into multiple outputs (AJAX, PHP) (nested AJAX requests, AJAX inside AJAX loop?)

Seeking advice on how to efficiently handle PHP output in small chunks for AJAX responseText. The project involves a webpage using AJAX to input a last name, which is then processed by a PHP program. The PHP code randomly selects three people with differen ...

A React-based frontend solution designed exclusively for managing data structures and databases

Challenges with Product Management In my React App, the shop features products sourced solely from a JSON file as an external API, all managed on the frontend. Recently, I encountered a product with limited availability - only 20 pieces in stock. I am uns ...

JavaScript Question: How can I extract the click value from a JavaScript visualization when displayed in a table?

I am working with a Hierarchical Edge Bundling visualization in JS. My goal is to have the name of the value displayed on the table when I click on it. Currently, I am facing an issue with retrieving the value dynamically. If I manually input a value, I c ...

retrieve essential data from Firebase using JavaScript

Currently, I am utilizing the get() method to retrieve data in my React Native application. Here is the code snippet that I am using: firebase .firestore() .collection("users") .doc("test") .get() .then(response => { console.log(respo ...

Notification from Socket.io following completion of database update

Can messages be sent to all users when the admin makes changes to the database, for example using the alert function? Scenario: Users are browsing car offers and while doing so, the admin changes the prices of a few offers --> users receive notificatio ...

Switching the class or modifying the style of an element when it is clicked in Vue.js

The process of retrieving data can be quite intricate. I have an array called "tweets" where the data is stored, and each tweet is represented as a card. I am able to successfully change the style of a card when it's clicked using the markTweet functi ...

Guide to designing a single-row table with varying numbers of columns and ensuring alignment is in place

I currently have a table displayed https://i.sstatic.net/20gZm.png The issue arises when I input large amounts of data, causing the structure to become irregular as depicted above. My query revolves around maintaining proper alignment within the table eve ...

When should you utilize both the compile and link functions within Angular to achieve your desired outcome?

I recently created my own custom directive in Angular, which is a new experience for me. app.directive('customer',function() { var directive = {}; directive.restrict = 'E'; directive.template = "Customer name : <b> {{customer.c ...

Express router route encountered a 404 Error

The first API endpoint is functioning correctly, however when attempting to access the second route, I am encountering a 404 error. Upon sending a GET request to http://localhost:3000/api/posts/, the response received is as follows: { message: "TOD ...