Ensuring a Memory Leak-Free Environment: Tips and Tricks

Here is my code, and I'm curious if the delete function effectively destroys an object without causing any memory leaks:

class Projectile extends MovableObject{
constructor(){
    super();
    this.speed = 2;
    this.geometry = new THREE.CircleGeometry(0.5);
    this.material = new THREE.MeshBasicMaterial({ color: 0xffffff });
    this.mesh = new THREE.Mesh(this.geometry, this.material);
}

setRotation(rotation){
    this.mesh.rotation.set(rotation.x, rotation.y, rotation.z);
}

setPosition(position){
    this.mesh.position.set(position.x, position.y, position.z);
}

}

Later on, I have a function called handleProjectiles where I manage instances of Projectile:

var position;
listProjectiles.forEach(function(projectile, i, list){
    position = projectile.getMesh().getWorldPosition();
    if(/*need to destroy the projectile*/){
        list.splice(i, 1);
        scene.remove(projectile.getMesh()); // This is ThreeJS
        delete projectile;
        console.log("Projectile has been destroyed");
    }
});

Answer №1

Although I may not have a complete answer, one thing is certain: you cannot delete variables that are part of a closure.

var myfunc = function(a, b, c) {
  console.log(a,b,c);
  delete b;
  console.log(a,b,c);
}; 

myfunc(1,2,3);

The code above will display the following:

1 2 3
1 2 3

When it comes to garbage collection in closures, you can refer to this related question.


If needed, you can always assign undefined to the variable.

var myfunc = function(a, b, c) {
  console.log(a,b,c);
  b = undefined;
  console.log(a,b,c);
}; 

myfunc(1,2,3);

This will result in:

1 2 3
1 undefined 3

Answer №2

One effective way to disconnect the shoot variable is by simply assigning it a value of null as shown below:

shoot = null;
console.log("The shoot variable has been successfully destroyed");

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

Using npm to install packages with multiple package.json files

My current project includes a submodule with another submodule, each having their own package.json file. This is how I set up my project: |root ----|node_modules ----|package.json ----|someFolder ----|submodule_1 -------- |package.json -------- |someFold ...

Create a 3D visual display with the use of three.js in Javascript

I'm navigating my second round with three.js and have been experimenting for a good 3 hours. However, I seem to be at a loss when it comes to determining my next steps. My goal is to create something similar to the layout found here: I've manag ...

Utilizing the Bing Translation API to translate an entire webpage

I am currently attempting to use the Bing API to translate an entire webpage instead of using the Bing widget. This is because I want to create a custom design for the translation panel, However, I have been unable to find any resources on how to do this ...

Endless cycle occurs when an asynchronous action is dispatched within useEffect

I encountered a never-ending loop problem when I added a dispatch function in my code within the useEffect hook. Despite looking into similar issues raised by others, I still can't seem to figure out the root cause of the problem. Here is how my compo ...

Adjusting the size of a popup window using resizeTo method functions properly when entering commands directly into the console, but encounters issues when executed within

I have researched this issue extensively and attempted various solutions, but I am still unable to grasp why resizeTo is not functioning in my particular scenario. I discovered that resizeTo works when the popup is generated by window.open, and I followed ...

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. ...

If the next element in the sequence happens to be the final element, then conceal a separate

Continue pressing the downward button consistently on until you reach the bottom. The down arrow should disappear slightly before reaching the end. Is there a way to achieve this using the code provided below? I'm new at this, but I believe I need t ...

Creating an object key using a passed literal argument in TypeScript

Can the following scenario be achieved? Given an argument, how can we identify the object key and access it? Any potential solutions? async function checkKey(arg:'key1'|'key2'){ // fetchResult returns an object with either {key1:&apo ...

Angular.js update URL on ng-click

After reading various posts on the same subject, I am still struggling to get my own code to work. My goal is to change the location of my app upon a ng-click event. Here is the html code I have: <button class="button icon-left ion-plus-round button-bl ...

Using a string as a query parameter in Javascript/AngularJS

Hey there! I have a username that I'm passing to retrieve a record from the database. Here's what I have in my controller: $scope.team=function(data) team_factory.getMember.query({}, data.username, function(data){ $scope.team=data; }); And ...

When you refresh the page, the number of items in the cart displayed on the navbar always shows 0

When using my angular application, I encountered a problem with adding movies to a cart. Although I can successfully add them to the cart and see the correct number of movies reflected in the navbar, upon refreshing the page, the count resets to 0. Here i ...

In search of a comprehensive AJAX-enabled content management system

Is there a Content Management System (CMS) available that can create a fully ajax-driven website, allowing for a persistent Flash component without the need to reload it with each page navigation? ...

Executing MySQL queries synchronously in Node.js

When working with NodeJS and mysql2 to save data in a database, there are times when I need to perform database saves synchronously. An example of this is below: if(rent.client.id === 0){ //Save client connection.query('INSERT INTO clients (n ...

Ensure that the vue-router guard waits for the completion of the axios API call in Vuex before proceeding

I am currently working with a django-rest-axios-vuejs application stack, and I have a specific task that involves the vue-router. Within the beforeEach guard of the vue-router, I am checking permissions by verifying something in the me object within the v ...

Guide to setting up a back button to return to the previous page in an iframe application on Facebook

I've developed a Facebook application that is contained within an IFRAME. Upon opening the application, users are presented with the main site, and by clicking on the gallery, they can view a variety of products. The gallery includes subpages that lo ...

Error encountered with Angular version 4: Unexpected token export

Upon starting the app with the command ng serve, I encountered an error in the console: VM1018:2297 Uncaught SyntaxError: Unexpected token export at eval (<anonymous>) at webpackJsonp.../../../../script-loader/addScript.js.mod ...

Create a receipt by utilizing jQuery with dynamically generated inputs

Is there a way to insert the descriptions and amounts of invoice items into the receipt, similar to the due date? The input for this section is dynamic with multiple rows that can be added or deleted. I'm considering using a counter that increments e ...

Apply CSS using JQuery at the start of an event and then revert it back at the end

Is there a way to notify users that the site is loading while a function with noticeable execution time is running? I have an associated change function which is connected to a drop down filter used for sorting through data on the page. $("#job_group").ch ...

What separates the functions `useRef` and `createRef` from each other?

As I was delving into the hooks documentation, I came across useRef. Upon examining their example… function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` refers to the mounted text inpu ...

Arrange pictures and div elements in a horizontal layout

I am facing an issue with my code that is displaying 5 'cards' in a messed up layout instead of a straight line. I have tried to align them vertically, but some are still higher and not in the right positions. For reference, I want the layout to ...