The JavaScript linked list causes the program to come to a halt

I am currently working on developing a simple web page embedded program using JavaScript. One of the tasks I am tackling involves creating a linked list of all active buttons displayed on the screen at any given time. However, I have encountered an issue where the program freezes when I try to iterate through a non-empty linked list.

Here is the section of code relevant to the problem:

document.addEventListener("click", (event) => {

        if (seekButtons) {

            if (!(activeButtons.isEmpty())) {
                var runner = activeButtons.head;

                /*
                 * 
                 * This while loop seems to run endlessly if the activeButtons list contains items.
                 * 
                 */ 
                while (runner) {
                    //this list should only contain buttons
                    console.log("a button! \n");

                    if (runner.element.isInside(mouseX, mouseY)) {
                        document.getElementById("fiddleText").innerHTML = ('clicked');
                        console.log("We are in the button! \n");

                        //This line doesn't seem to work as intended. It should move to the next item in the list (and exit the loop if it's the last item), but the loop runs indefinitely.
                        runner = runner.next;
                    }
                }
                

            }
            
        }
    });
    

I believe another set of eyes could help identify the reason why this code is not functioning correctly.

The linked list implementation code (not authored by me) appears as follows:

// Implementation of a LinkedList in JavaScript

class Node {
    constructor(element) {
        this.element = element;
        this.next = null;
    }
}

class LinkedList {
    constructor() {
        this.head = null;
        this.size = 0;
    }

    // Additional methods implemented within the class
    // ...
}

The main code section looks like this:

// Initialization of canvas elements and other variables
var canvas = document.getElementById("SnekGamCanvas");
var ctx = canvas.getContext("2d");
canvas.addEventListener('click', function () { }, false);

var px = canvas.width / 2;
var py = canvas.height / 2;

var snekColor = "#EC942D";

var clock = 0;

var mouseX = 0.5;
var mouseY = 0.5;

var activeButtons = new LinkedList();

var seekButtons = true;

// Definition of a class for clickable buttons
class clickButton {
    // Functions and properties of the class
    // ...
}

// Initialization of buttons and images
// ...

// Additional code for mouse interactions and game states
// ...

// Entry point for the game
function draw() {
    clock += 1;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // Game state logic
    // ...
}
setInterval(draw, 10);

function setup() {
    // Initialization of activeButtons list
    // ...

    gameState = 0;
}

// Other game state functions
// ...

// Display of canvas and additional functionality
// ...

Furthermore, the CSS and HTML files that I am utilizing for this project are as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Head content -->
    <!-- ... -->
</head>
<body class="background_gradient">
    <!-- HTML content -->
    <!-- ... -->
</body>
</html>

Thank you for reviewing this information, and any insights or feedback would be greatly appreciated.

Answer №1

If the current runner is not inside the button, the loop gets stuck on that element and continues to loop endlessly before moving on to the next runner.

To fix this issue, remove the line runner = runner.next; from the if statement.

            while (runner) {
                //this list should be populated only by buttons
                console.log("a button! \n");

                if (runner.element.isInside(mouseX, mouseY)) {
                    document.getElementById("fiddleText").innerHTML = ('clicked');
                    console.log("We are in the button! \n");
                }
                runner = runner.next;
            }

Consider using a for loop for a more straightforward approach:

for (let runner = activeButtons.head; runner; runner = runner.next) {
    if (runner.element.isInside(mouseX, mouseY)) {
        document.getElementById("fiddleText").innerHTML = ('clicked');
        console.log("We are in the button! \n");
    }
}

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

Changing a JavaScript command into a text representation

Currently, I have an array stored in a variable as shown below: arr = [1, 2, 3] Is there a way to convert this array statement into a string like this? newArr = "arr = [1, 2, 3]" ...

Modify the bootstrap dropdown background to display only an image

I am looking to make the image in a dropdown/dropup menu fill the entire background of the dropdown. Currently, there is still white space visible around the image. How can I ensure that the dropdown shows only the image and includes a scroll wheel? Addit ...

Enhance your MUI treeview by incorporating stylish connecting borders

I've been trying to add borders that connect to the nodes in the mui treeview, but I'm having difficulty with not having a vertical border when it's the last leaf node. It currently looks like this: See border example here. However, it sh ...

When creating a FlipCard, you may encounter the error message "The object may be null" while using the document.querySelector() method

Having trouble creating a flipcard on Next.js with tsx. The querySelector('.cardflipper') doesn't seem to locate the object and I keep getting this error: "Possibly the object is null". Does anyone know a solution to help my method recognize ...

Animating Text with CSS for Different Message Lengths

I have been exploring alternatives to the marquee tag and discovered a way to achieve this through CSS. However, the messages I am working with vary in length. Is there an alternative to setting the '45s' attribute to maybe 100% so that regardles ...

Having a problem with file uploads in node.js using multer. The variables req.file and req.files are always coming

I am encountering an issue with uploading a file to my server, as both req.file and req.files are consistently undefined on my POST REST endpoint. The file I'm attempting to upload is a ".dat" file, and my expectation is to receive a JSON response. ...

What could be causing this Ajax error I'm experiencing?

I am attempting to dynamically load pages on this website using JQuery and Ajax when a menu point is clicked. However, I am encountering errors during the loading process. What does the console message ""GET 'path to css file'" mean? (there ...

The problem persists as Vite is failing to load CSS codes enclosed within VUE components

My project is developed using Laravel, Inertia.js with Vue, and Vite for bundling the frontend assets. Everything seems to be working fine with the application, except when I try to access it from a subdirectory. In this scenario, Vite fails to load the C ...

Changing the background color of the dropdown button in Vue Bootstrap: A step-by-step guide

I've been struggling to modify the background color of a dropdown button, but no method seems to work. I've attempted changing it by using ID, removing its class and applying a new one, and even using !important to override the styles, but the ba ...

Guide to implementing a personalized filter in AngularJS 1.6

I am struggling with injecting a custom filter, status, into my component. Below is the code for my component: function ClaimsListController(dpClaimsListService) { var ctrl = this; ctrl.claims = null; ctrl.searchCriterion = null; ctrl.l ...

Obtain every Scope within an AngularJS application

Is there a method to access all the Scopes within an AngularJS application? This would allow me to manage them at the same level and arrange them in a directive manner or order. Alternatively, is it possible to retrieve all the Scopes of the instances of ...

Analyzing cookie data and utilizing jQuery for data presentation

Let's brainstorm. I'm currently working on a chat bar and have successfully implemented its functionality. However, I am facing a challenge in maintaining the continuity of the chat boxes while navigating through different pages on the website. ...

Tips for Testing an Ajax jQuery Function Within the document.ready Event

I am in the process of developing a script that utilizes $.ajax to make requests for a json api. My goal is to create unit tests that can verify the results received from the ajax request. For instance, I expect the returned JSON object to contain "items" ...

Refreshing jQuery via Ajax Response

In our JSF2 application, we encounter situations where we need to re-invoke the JavaScript (specifically jQuery for UI styling) when making Ajax calls. However, it seems that the JavaScript functions are not being called upon receiving the Ajax response fr ...

I noticed that my regular expression is functioning correctly on regex101, but for some reason, it's

My search works perfectly on regex101 using this link: https://regex101.com/r/z8JCpv/1 However, in my Node script, the third matched group array[2] is returning not only the matching text but also everything following it. An example line from the source ...

Automatically advance to the next input field and go back when the backspace key is pressed after reaching the maximum length

Creating a credit card input field that switches cursor after reaching maximum number length and focuses on previous field when deleting with backspace. (function ($) { $(".nmipay-input-field").keyup(function () { if (this.value.l ...

The element div is not permitted as a child of the element h5 in this particular scenario

My code snippet is as follows: $compile .= "<h5 data-count='".$acctemmpi. "' class='shortcode_accordion_item_title expanded_". $expanded_state . "'>" . $title . "<div class='ico'&g ...

What is a PHP self-generating variable?

Is it possible to use a form variable as its own URL? It may be difficult to explain, but here's an example: matchmaking.php: $search_summoner = $_POST['search_summoner']; echo '<form method="post" action="matchmaking.php?searc ...

What is the correct way to insert a new key-value pair into an object within the state of functional components?

Is there a way to dynamically add key-value pairs to the initial state of an empty object in functional components, similar to computed property names in class components? I currently have an initial state of {}. const [choice, setChoice] = useState({}) ...

Determine if two instances are within the same week, where each week starts on Friday and ends on Thursday, using moment.js

Currently, I'm in the process of developing a Discord bot using node.js and discord.js. One of the features allows users to vote through a command, but I want to restrict them to voting only once per week. The challenge lies in the fact that in this ...