JavaScript code causing the page to freeze

I am attempting to track the movement of a dynamic div (which is animated using CSS3 animations) by continuously monitoring its position. To achieve this, I have implemented a loop utilizing while(true) as shown below:

function detectCollision(){

    alert(document.getElementById("obstacle").style.left)

    while(true){
        var temp = getObstaclePosition();

        var temp2 = getPlanePosition();
        if(temp[0] <= temp2[0]+500){
            document.getElementsByClassName("plane")[0].style.display = "none";
            break;
        }
    }
}

The issue arises after displaying the first alert since the page becomes unresponsive. Additionally, introducing an alert within the while loop results in continuous popping alerts but ensures that the code functions correctly. How can I address this problem?

Answer №1

A more efficient alternative to a while (true) loop is using the setInterval method:

b = setInterval(() => {
    let obstaclePos = getObstaclePosition();
    
    let planePos = getPlanePosition();
    
    if(obstaclePos[0] <= planePos[0] + 500) {
        document.querySelector(".plane").style.display = "none";
        clearInterval(b);
    }
}, 100);

Answer №2

The element's position remains static within the loop, causing the page not to render and leading to an infinite loop.

To achieve this functionality, you can utilize either a recursive setTimeout or a traditional setInterval.

These methods allow for one iteration per timeout period.

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

Answer №3

When running JavaScript, it operates within a single thread. This means that if a loop is stuck in an infinite loop, it will prevent the rest of the code from executing.

Instead of using a traditional loop, another option is to utilize setInterval, which allows for the repetitive execution of a function or code snippet:

setInterval(new function() {
    // insert desired code here
}, 100); // repeat every 100 milliseconds, equivalent to 10 times per second

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

I am experiencing issues with md-no-focus-style not functioning correctly in my configuration

I have a button that triggers the opening of my navigation bar: https://i.sstatic.net/nMr0i.jpg When I click on it, a hitmarker appears: https://i.sstatic.net/OLQaE.jpg The issue is that even after clicking on a navigation item and transitioning to the ...

The installation of [email protected] for Firebase in expo-cli React Native did not succeed via npm

During my attempt to integrate the firebase package into my expo project for authentication purposes, I encountered difficulty as the installation process failed and produced unexpected errors. The following command was used to install the firebase packag ...

When utilizing CKEditor in conjunction with ExpressJS, HTML tags may be displayed in the browser

Check out my app.js code below: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0> <meta http-equiv="X-UA-Compatible" content="ie= ...

The unfortunate timing of the multi-material design lite snackbar

I am currently working on customizing notifications that appear when a Symfony entity is successfully updated. What I have implemented so far can be found here : var messagesTypes = { "notice": ["This is a green NOTICE"], "error": ["This is a red E ...

Creating Dynamic Panel Animations in XUL for Your Firefox Extension

Recently, I created a Firefox Add-On for my company's IT Ticket System. This add-on notifies managers of new tickets and alerts users about any changes to their existing tickets. Initially, I used the default notifier for Firefox on Windows with: var ...

How do I access and read a map within an array from Firebase using ReactJS?

I have an array that contains a map with two values: title and content. https://i.stack.imgur.com/WLWVG.png I am trying to read all the values in the array as if it were a map. However, I have attempted this code without success. Can anyone assist me? {d ...

Error: Unable to locate corresponding closing tag for "<%"

I'm struggling to figure out what I might have missed. Everything appears correct, but the nested and somewhat complex code that I am writing seems to be causing an issue with EJS. The variable posts has been passed from node.js to the EJS file. How c ...

Opt for JavaScript DOM manipulation over jQuery for element selection without depending on jQuery

I am attempting to target a specific element using JavaScript: element = '<div class="c-element js-element">Something Here</div>'; When I try to select this element with the following code: $(element) The result is not as expected ...

Using Vue.js: Is there a way to apply scoped CSS to dynamically generated HTML content?

Summary: I'm struggling to apply scoped CSS styling to dynamically generated HTML in my Vue component. The generated HTML lacks the necessary data attribute for scoping, making it difficult to style with scoped CSS rules. Details: In a function cal ...

Ensure that JavaScript functions are executed sequentially without overlapping

Important : Absolutely no jQuery allowed I have developed four distinct functions and I am looking to execute them sequentially, one after the other in JavaScript without using jQuery. I have scoured the internet for a solution but unfortunately have not ...

Repeated Identification Numbers in Mongoose Database

I have created a virtual object with a duplicated ID and I'm struggling to find a solution using the new syntax. Can anyone offer assistance? /** * Import only the mongoose in this class * This plugin is for MongoDB and this class decide how the Mon ...

Unable to retrieve member information using Three.js in TypeScript

I am currently using three.d.ts from DefinitelyTyped along with TypeScript. Below is the code snippet I have: class WoodStyle extends THREE.MeshBasicMaterial{ putTexture(image: any){ super.map=image; } constructor(){ LoadImage( ...

What's the best way to adjust the height of a textarea to completely fill the column?

Currently, I am in the process of creating a simple contact form using Bootstrap-4. The layout consists of 1 row with 2 columns: the left column contains input text fields and selection menus, while the right column includes a textarea. The challenge I&apo ...

JavaScript - unique user-defined data types - what skills do I need and what knowledge should I acquire?

Exploring the vast flexibility of JavaScript, I've been intrigued by the idea of creating a custom data type that mimics the behavior of native JS types. My goal is to develop a range data type capable of representing math ranges such as (2.5;9] or (- ...

Choose all stylus/css imports except for those with a specific ending

How can a rule be correctly written in a .styl file to import all files from selected folders except those that contain the -ie suffix (e.g. bar-ie.style)? What is the best way to achieve this? The code below is not functioning as expected: import([&apos ...

Issue with close request on dialog box

Whenever an icon is clicked, a dialog box containing a form should appear. The purpose of this dialog box is to either add a new tab or delete a specific tab. In my implementation, I used ReactJS, Redux, and Material-UI for building the components. Even th ...

Ensure that you accurately maintain object ids following the creation of elements using ng-repeat

I have a set of items listed with unique objects within my controller $scope.itemsList = [ {"id": 0, "item": "sw", "category": 'A' }, {"id": 1, "item": "mlr", "category": 'B'}, {"id": 2, "item": "lvm", "category": 'C&a ...

Issue encountered in Meteor/React app: Error message "ReferenceError: require is not defined" or "Error: Cannot

I am currently working on a school project that requires the use of Meteor with React. I have built a website and now I want to include a carousel feature. In order to achieve this, I attempted to utilize the following library: https://github.com/vazco/me ...

Creating an interactive timer that counts down in real-time using a combination of Django and JavaScript

When passing the date and time from views.py to my HTML page, I am encountering difficulties in utilizing that information to create a countdown timer using Javascript. For example: return render(request,'page.html',{'date':i.date,&apo ...

Husky 5: The Ultimate Gitignore Manager

Last week, a new version of Husky was released, known as Husky 5. I came across an interesting article discussing the features and updates in this release that can be found here. Upon migrating to Husky 5 (), I discovered a new directory named .husky with ...