Issues encountered in loading JavaScript with jQuery script

I am facing an issue with my jQuery script not loading correctly. When I click on the calculate button, nothing happens as expected. I made sure to copy and paste jQuery directly into the file for offline use, and also created a personal console due to restrictions on the school laptop where I usually work on this project when bored.

The problem isn't with jQuery itself as I have managed to run it previously without any issues.

Upon inspecting the code, it seems like there might be an infinite loop causing the page to freeze and the CPU usage to spike when the script loads and the calculate button is pressed according to the task manager. I am at a loss as to what could be causing these complications and would appreciate some help.

I understand that there may be better ways to achieve my goal, but please keep in mind that I am doing this project for fun. Despite spending quite some time on it during my spare moments, I haven't been able to figure out if I am making mistakes or if the code itself needs reworking.

The aim of the script is to increase the limit of the maximum number recognizable by pushing it from around 54 billion to 54 billion digits long. However, as mentioned earlier, the script fails to load properly.

<span id="console"></span>
<form>
    <input type="radio" id="add" name="mathtype" checked="checked"> Addition (in development)<br>
    <input type="radio" id="sub" name="mathtype"> Subtraction (Unavailable)<br>
    <input type="radio" id="multi" name="mathtype"> Multiplication (Unavailable)<br>
    <input type="radio" id="div" name="mathtype"> Division (Unavailable)
</form>
<br>
Number: <input type="text" id="input1">
<br>
Number: <input type="text" id="input2">
<br>
<span id="extraInputs"></span>
<button id="addInput">Add another input field</button>
<br>
<button id="calc">Calculate...</button>
<br>
<p id="output">Press "Calculate..."</p>

<script>/*This is where I load the jQuery*/</script>

<script>
    document.getElementById("console").innerHTML("<div class='info'>Script ran</div>");
    "use strict";
    $(document).ready(function(){
        try {
            var page = $("#console");
            var log = function(message) {
                page.append('<div class="log">'+message+'</div>');
            };
            var info = function(message) {
                page.append('<div class="info">'+message+'</div>');
            };
            var warn = function(message) {
                page.append('<div class="warn">'+message+'</div>');
            };
            var error = function(message) {
                page.append('<div class="error">'+message+'</div>');
            };
            log("Doc and console up");
        } catch(err) {
            document.getElementById("console").innerHTML("<div class='error'>ERROR WITH LAUNCHING CONSOLE.</div>");
        }

        try {
            var inputBoxes = 2;

            var add = function(num1, num2) {
                log("Running add");
                var neg = [0, false, false];

                num1 = num1.split("-");
                num2 = num2.split("-");
                log(num1);
                log(num2);

                if(num1.length == 2) {
                    num1 = num1[1];
                    neg[1] = true;
                } else {
                    num1 = num1.toString();
                }
                if (num2.length == 2) {
                    num2 = num2[1];
                    neg[2] = true;
                } else {
                    num2 = num2.toString();
                }

                log(num1);
                log(num2);
                info(neg);

                var isNeg = false;

                if(((neg[1] || neg[2]) && (neg[1]!=neg[2])) == true) {
                    isNeg = true;
                }
                log(neg);

                num1 = num1.split('');
                num2 = num2.split('');
                log(num1);
                log(num2);

                var maxChar = Math.max(num1.length, num2.length);
                log(maxChar);

                if(maxChar > num1.length) {
                    for(var i=0;i<maxChar-num1.length;i++) {
                        num1.unshift("0");
                    }
                } else if (maxChar > num2.length) {
                    for(var i=0;i<maxChar-num1.length;i++) {
                        num2.unshift("0");
                    }
                }

                var final = [];
                var time;
                var carry = 0;

                for (var i=maxChar; i>0;i--) {
                    if(time != i++) {
                        carry = 0;
                    }

                    final[i] = (parseInt(num1[i]) + parseInt(num2[i]) + parseInt(carry)).toString();

                    if(parseInt(final[i]) > 9) {
                        var temp = final[i].split('');
                        final[i] = temp[1];
                        carry = temp[0];
                        time = i;
                    }
                }

                if(isNeg){
                    final.unshift("-");
                }

                info(final.join());
                return final.join();
            };

            $("button#addInput").click(function(){
                inputBoxes++;
                $("#extraInputs").append('Number: <input type="text" id="input'+inputBoxes+'"><br>');
            });

            $("#calc").click(function(){
                info("Checking conditions...");
                if ($("#add").is(":checked")) {
                    info("Running...");
                    info($("#input1").val());
                    info($("#input2").val());

                    var final = add($("#input1").val(), $("#input2").val());
                    info("Ran");
                    if (inputBoxes > 2) {
                        info("inputBoxes: "+inputBoxes.toString());
                        for (var i=3; i<inputBoxes; i++) {
                            final = add(final, $("#input"+i.toString()).val());
                        }
                    }
                    info(final);
                    $("#output").text(final));
                }
                log("Functions up");
            });
        } catch(err) {
          error(err);
        }
    });
</script>

The primary objective of this script is to perform addition operations on multiple numbers while aiming to stay within the constraints of the language's understanding capacity, allowing for larger computations.

Answer №1

I'm not sure about the purpose of your code, but it seems like you've unintentionally created an infinite loop here:

for (var i=maxChar; i>0;i--) {
    if(time != i++) {
        carry = 0;
    }

During each iteration, the value of i is being both decreased and increased by one, causing it to maintain the same value and preventing the loop from ever ending. It appears that you might have intended to check if (time != i+1) instead.

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

Is there a way to direct Webpack in a Next.JS application to resolve a particular dependency from an external directory?

Is it possible to make all react imports in the given directory structure resolve to react-b? |__node_modules | |__react-a | |__app-a | |__component-a | |__next-app | |__react-b | |__component-b // component-a import { useEffect } from ' ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

The map loop is failing to display anything, despite the presence of data

My React component is making a call to a PHP endpoint that returns an array of folders in a directory for an internal forms file browser. The API call is successful, and the response is correct. However, when I try to map over the array, nothing is being r ...

Using Bootstrap's dual listbox, you can easily select single options with the ability to add or delete them. Upon selection, the

Could someone please assist me in resolving this issue? I am looking for a dual listbox with single select option, unlike Bootstrap which only offers dual listboxes with single/multiple select. To Clarify: Here is an example: In my dual listbox, the le ...

Design a stylish table using the format from the specified file

Currently, my goal is to generate a table using data from a csv file. The csv file contains three pre-filtered fields to avoid any issues. However, when I execute the code, no output is generated in the report file. I suspect there may be an error while pr ...

Adjust the Placement of Images in Relation to Mouse Movements

Is there a way to creatively animate the positions of images or background images based on mouse movement? Let's take Github, for instance: https://github.com/thispagedoesntexist The 404 page on Github is truly impressive. I aim to captivate my use ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

Steps for embedding a font in a .pptx file

While working on creating a .pptx file using ASPOSE.Slides, I encountered some issues with embedding fonts. As an alternative option, I am looking for suggestions on how to embed custom fonts in a .pptx file using Apache POI or other methods. If you have ...

Warning from Vue: Steer clear of directly changing a prop as it will be replaced whenever the parent component undergoes re-rendering

I've been diving into Vue.js, but I'm encountering an issue. Every time I try to click on the "edit age" or "change my name" button, I get the following error message. [Vue warn]: Avoid mutating a prop directly because the value will be overwrit ...

Getting an error message of 'Unable to locate Firebase Storage Default Bucket on the server?

I'm currently facing an issue with the server not being able to locate the bucket. To troubleshoot, I've stored the token and other crucial details in a separate file as a string. Afterwards, I split it and utilize the relevant text in my Javascr ...

Swiper: What methods can be used to classify the nature of an event?

Currently, I am utilizing Swiper for React in my project. I find myself in need of implementing a different effect when the user swipes versus using buttons to switch between active slides. Upon examining the swipe object for pertinent details regarding ...

Server Error: Reactjs doesn't support posting images

I am experiencing an issue in my ReactJS project. When I attempt to upload an image using react-images-uploader, I encounter the following error: "Cannot POST /images error" Below is the code snippet for the image upload: <ImagesUploader ur ...

Design element: Text overlaying background with a touch of transparency

Is there a way to create a background image with an opacity level of 0.5, while maintaining the text on top at full opacity (1) for better readability? Currently, the background image is not displaying as desired, and the opacity settings are affecting the ...

Combining Rails 3.1 authenticity tokens with the uploadify feature

Currently, I am facing an issue while trying to integrate Uploadify with my Rails 3.1 application. Despite setting up all the necessary steps such as middleware, initializers, and configuration, everything seems to be working correctly except for one parti ...

What is the best method for dividing a user interface into several arrays of keys, each grouped by type?

Given a simple structure: structure IPerson { firstName: string; lastName: string; age: number; city: string; favoriteNumber: number; isMarried: boolean; hasDriverLicense: boolean; } How do I create arrays containing keys grouped by data typ ...

Expanding your JavaScript skills: Tackling nested object key and value replacements

I am looking to manipulate the values of a nested object using JavaScript. The structure of the object is outlined below. let jsonObj = { "service":[ { "name":"restservice", "device&quo ...

Manipulate the contents of children divs within a parent div using JavaScript or JQuery

<div id="abc"> <div id="a_b"> abcd </div> <div id="c_d"> xyz </div> </div> I have a challenge where the divs on my page are generated dynamically and their IDs change every time the page loads. When the window i ...

Extract the chosen document from an input within the Electron application form

Need help with this form <form> <input type="file" name="idp" id="idp" onchange="uploadFiles();"/> </form> Once a user selects an image, I want to move it to a specific folder and save its full name in a variable for database storage. ...

What steps should be taken to enable the "You and moderator can reply" feature in a bot when sending proactive messages to channels?

A project I am currently working on involves creating a bot that sends proactive messages to channels. The client has requested that I include options like No reply or You and moderator can reply with the messages posted by the bot proactively. Here is wh ...

Guide to positioning text alongside icons with Bootstrap

Struggling to align text next to these icons? Don't worry, we've all been there. Especially with bootstrap - it can be tricky! Can someone please guide me on how to do this? <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstr ...