Exploring the relationship between variables and closure scope in the context of anonymous

Each time the anonymous function is invoked with a parameter, it encapsulates everything within itself. If another call to the subscribed function occurs before the first anonymous function's callback from the database or ajax call, it will not affect the previous anonymous function. The current anonymous function creates a new closure for each call, ensuring that data for each closure remains isolated and unaffected by other closures.

this.subscribe.call(this, e.horizontaladded, function(a, fn) {
    if (!a.extra.owner.id) { return; };
    (function(a) {
        dataBase.insert(
            dbPart(['horizontal?a=', a.extra.owner.instanceName, '&id=', a.extra.owner.id].join(''),
            a.target),
            dbCB(success, error)
        );
        
        function success(data, status) {
            if (status === 'error') { return; };
            console.log('Horizontal Added');
            a.target.id = data.id;
            a.target.HTML().addClass('alum_' + data.id);
            a.target.finish.id = data.finishID;
            a.target.size.id = data.sizeID;
            a.target.siteLine.id = data.sitelineID;
        }(a));
    }, true);

In essence, every invocation of the e.horizontaladded I am subscribed to triggers a new anonymous function which closes up with its own set of personal data. Garbage collection takes care of cleaning up these closures individually.

Therefore, if 30 calls are made to the function I am subscribed to, resulting in 30 closures being created, each closure will clean itself up once the database success callback is triggered.

Answer №1

The garbage collector takes care of cleaning up a closure when there are no longer any connections to the variables contained within it.

Essentially, a closure is treated the same as any other object in javascript by the garbage collector. Once all references to objects within the closure have been removed, the garbage collector can dispose of it.

In a specific scenario like yours where an immediately invoked function expression creates a closure, the closure will persist as long as there is still a reference to it in the code. For example, if the database.insert() function has a connection to the success() function inside the closure, the closure will remain active. However, once the success() function is called and the reference is released, the closure becomes eligible for cleanup by the garbage collector if no other connections exist.

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

Vanishing message when clicked in PHP

I created a code to display error messages and success messages based on user input, allowing them to click anywhere on the screen to dismiss the message. The issue I am facing is that when the user receives both a success and an error message simultaneo ...

Activating two buttons in jquery will trigger this action

I am currently working on developing a filter button that will perform different actions based on which buttons are pressed. Pressing button1 will trigger one action, while pressing button2 will trigger another action. If button1 is pressed first, followe ...

Exploring the wonders of Angularjs and the dynamic capabilities of streaming data

Using AngularJS's $http to request streaming data like this: $http({ method: 'POST', url: url, data: JSON.stringify(data), headers: config }).success(function(responseData) { console.log(responseData); }).error(funct ...

Using JS or jQuery to organize JSON data into a multidimensional array

Dealing with frontend processing of a response from a server that provides event reviews for the season has been challenging. In this case, there can be multiple reviewers for the same event and the simplified version of the response appears as follows: [ ...

Transfer information through req.body from one HTML file to another using Express

I'm having an issue with importing data from a form page on my express server. Currently, the home get request leads to a form page and after submitting the form, the data is stored in req.body as a JSON. I can successfully log this information to th ...

How can curly braces be utilized in an array reduce method?

If the function `fn3` is used instead of `fn2` in this code snippet running on node 9.5.0, the `console.log(totalUpvotes)` will display `undefined`. Shouldn't it actually be equal to 92? const posts = [{id: 1, upVotes: 2}, {id:2, upVotes: 89}, {id: ...

Using jQuery to dynamically add a value to a comment string

Is there a way to dynamically include tomorrow's start and end times in the message for the setupOrderingNotAvailable function if today's end time has passed? The current message states that online ordering will be available again tomorrow from 1 ...

Issue: The automation server is unable to generate the object

I am encountering an issue with the code snippet below, which is causing an error specifically in the IE-11 web browser: var excApp = new ActiveXObject("Excel.Application"); The error message being displayed is: Error: Automation server can't create ...

Successfully running npm update on a Mac seemed to have updated the package, however, the

I needed to upgrade my npm version using the following command: npm install npm@latest -g After running the above command, I encountered the following output: /Users/ariful.haque/.npm-global/bin/npm -> /Users/ariful.haque/.npm-global/lib/node_modules ...

Managing and Streaming Music in a Rails Application

Currently, I am storing mp3s using paperclip and they only play back if I utilize Amazon S3. However, I am hesitant to use Amazon S3 because I am unsure how to secure the files. Now, I am reconsidering my approach as I need to secure the mp3s and provide ...

PHP Header Redirect Not Redirecting Correctly

As a newcomer to PHP, I conducted some research and attempted to implement a solution found on Stack Overflow, but unfortunately, it did not work for me. My goal is to redirect users to another page after a specific code has been executed. Despite removing ...

I need to update a JSON file on the server by adding a new object to the existing array using the fs.appendFile function

I have a JSON stored on the server like this: [{"a":1}, {"a":2}] and I'm wondering if there is a way to add an object at the end without having to rewrite the entire file on the server. As a workaround, I have been omitting the brackets and adding the ...

"Repeatedly encountering 'undefined' when subscribing to the selected option of a select list in Knockout.js

In my dropdown list, I have prepopulated a selection of strings. My select list is bound as follows: <select id="industryDropDown" data-bind="options: $root.orgIndustrySuggestions, value: $root.selectedIndustryTag, optionsCaption: ''"> ...

How to Utilize the Vue Instance With the 'this'

Trying to implement this in my VueJs methods results in an error message: this is undefined It seems like arrow functions may not be suitable as their this does not bind to the expected context. Switching to a regular function still causes the same err ...

Manipulating links using JQuery: avoiding the binding of new links

I need to update a website with 50 pages that currently doesn't use ajax, making it cumbersome to make edits since changes have to be made on all 50 pages individually. After removing duplicate HTML from all 50 pages, I'm facing some issues: fu ...

retrieve all users who are not currently in the group

I'm currently struggling to retrieve all users who are not members of a particular group within a many-to-many association. After investing several hours into researching and experimenting, I've developed the following code. However, it falls sh ...

How can I restrict Material UI TextFields with input type = file to only allow pdf files?

Is there a way to restrict users from uploading anything other than PDF files using input type=file? I've researched about using the accept attribute but seems like it's not compatible with material UI text fields. Is there an alternative soluti ...

Call the javascript function (provided as a parameter) from native iOS code

I am grappling with a JavaScript function structured like this. function getState(){ return "Hello"; } var cryptico = (function() { var my = {}; my.generateRSAKey = function(passphrase, bitlength) { Math.seedrandom(sha256.hex(passphr ...

The Chrome browser's memory heap is reported to be a mere 10 MB, yet the task manager displays a whopping

When using Chrome's memory profiler, I notice that the heap size is always around 10 MB. However, the memory in my task manager keeps increasing and can reach over 1 GB if I leave my website running. Even though the heap size remains less than 10 MB w ...

Challenges encountered when passing objects with Angular 2 promises

I am encountering a problem when using a promise to retrieve a Degree object in Angular 2. The initial return statement (not commented out) in degree.service functions correctly when paired with the uncommented implementation of getDegree() in build.compon ...