AJAX - Self-Executing Anonymous Function

I have a question that may seem trivial, but I want to make sure I'm heading in the right direction.

I've created two different versions of an XMLHttpRequest wrapper, and both are functioning correctly.

const httpRequest = function () {
    let xhr = new XMLHttpRequest();
    return function ( config = { url: '', method: 'GET', onLoadStart: null, onLoad: null, onProgress: null, onError: null, onAbort: null, onLoadEnd: null, onTimeout: null, timeout : null }) {

        xhr.open(config.method, config.url);
        xhr.onloadstart = config.onLoadStart;
        xhr.onload = config.onLoad;
        xhr.onprogress = config.onProgress;
        xhr.onerror = config.onError;
        xhr.onabort = config.onAbort;
        xhr.onloadend = config.onLoadEnd;
        xhr.ontimeout = config.onTimeout;
        xhr.timeout = config.timeout;
        return xhr;
    };
}();

and this one

function httpRequest(config = { url: '', method: 'GET', onLoadStart: null, onLoad: null, onProgress: null, onError: null, onAbort: null, onLoadEnd: null, onTimeout: null, timeout : null }) {
    var xhr = new XMLHttpRequest();

    xhr.open(config.method, config.url);
    xhr.onloadstart = config.onLoadStart;
    xhr.onload = config.onLoad;
    xhr.onprogress = config.onProgress;
    xhr.onerror = config.onError;
    xhr.onabort = config.onAbort;
    xhr.onloadend = config.onLoadEnd;
    xhr.ontimeout = config.onTimeout;
    xhr.timeout = config.timeout;

    return xhr;
}

I'm having trouble understanding why you would use an immediately-invoked Function Expression when a regular function works just as well? I'm hoping someone can provide some insight, as I've heard that for this type of scenario, an immediately invoked function is preferred.

Answer №1

The key distinction between the two methods lies in the timing of creating the XMLHttpRequest object.

In the first method, you invoke it in this manner:

h = httpRequest();
xhr1 = h({ ... });
xhr1.send(...);
xhr2 = h({ ... });
xhr2.send(...);

When calling httpRequest(), a single instance of XMLHttpRequest is created and shared between both xhr1 and xhr2.

This approach may lead to issues as assigning values to xhr2 will overwrite the properties of the original XMLHttpRequest object. Yet, if you can avoid invoking h() until the previous use is complete, it could help save some memory.

On the other hand, the second method involves directly calling httpRequest(), which generates a fresh XMLHttpRequest instance each time.

xhr1 = httpRequest({...});
xhr1.send(...);
xhr2 = httpRequest({...});
xhr2.send(...);

This technique is secure as there are no instances of overwriting involved.

If you modify the initial version by placing let xhr = new XMLHttpRequest(); at the start of the inner function, it will mirror the second technique while requiring slightly more verbosity when using it.

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

Constantly positioning the text cursor over the Textbox

I am currently in the process of developing a webpage that will feature only one text box for displaying information based on the input data provided. Our strategy involves utilizing either a Barcode Scanner or Magnetic Swipe as well as a Touch Screen Moni ...

Tips for accessing the current state/value in a third-party event handler?

Consider the following scenario: function MapControl() { const [countries, setCountries] = useContext(CountriesContext) useEffect( () => { ThirdPartyApi.OnSelectCountry((country) => { setCountries([...countries, country]) }) }) ...

What is the best way to retrieve attributes from a through table using a query?

I am in the process of creating a straightforward shopping cart system. My structure includes a Cart model, a Product model, and a connection table called CartItems. Here are the associations: models.Cart.belongsToMany(models.Product, { through: 'Car ...

The initial click event for the input element in Jquery is not functioning correctly

I found a jQuery date selector online and the script looked something like this... <script type="text/javascript> $(document).ready(function () { $("#date3").click(function() { $("#date3").scroller({ preset: 'datetime' }); wheels = []; whe ...

Use jQuery to permit only numeric characters and the symbol "-" to be entered into a textbox

I have been working on a JQuery script that only allows users to input numbers in a text field. However, I am now trying to modify the code to also allow users to enter "-" (hyphen), but so far it's not working as expected. If anyone can provide assis ...

Implement the Bootstrap datetimepicker functionality for the specified div element

The date picker successfully functions when I assign the id to the input tag as shown below: <div class="col-sm-4" id="datepicker"> <input type="text" class="form-control" id="inputDate" placeholder="Date"> <span class="glyphicon gl ...

Store the beginning and ending times in a MySQL database using Sequelize and Node.js

I am currently developing a project management application where I need to keep track of the start and stop time for user work. To achieve this, I have implemented two buttons in the UI - START and STOP. When a user clicks the START button, the following ...

Is there a way to showcase the content of a text file in a sequential manner using Javascript/AJAX?

I am attempting to retrieve text data from a server file and exhibit it within a specific division on my website. Check out the AJAX/Javascript code I have been working with: <body onload="loadXMLDoc()"> <script> function loadX ...

What causes the component to remount with every update to its state?

PLEASE NOTE: Before posting this question, I realized that there were some errors in my code. I understand now that this question may not be helpful to others as it contains misleading information. I apologize and appreciate those who took the time to res ...

Picture is currently not showing up in the division

I am currently working on an HTML page and I'm having trouble displaying an image within a division element. Below is the code snippet I tried: Here is the JavaScript part of my code: var filename = "andrew.png"; $("#detected").show().html('< ...

NextRouter does not have a property called "refresh"

Here is the provided code snippet: "use client"; import { useRouter } from "next/router"; import { useState } from "react"; export default function CreatePrompt() { const [title, setTitle] = useState(""); const ...

Displaying Text and Images on a Sliding Carousel with a Static Background Image

I am currently experimenting with the Materializecss Image Slider. My goal is to have a fixed full-screen background image while the texts and images slide over it. Initially, I tried setting the background-color of the slider class as transparent, but un ...

When I attempted to run `npm start`, an error with status code 1 was thrown,

Upon running npm start, the following error is displayed: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4c5d5d6d1d031c031d">[email protected]</a> start /Users/user/Desktop/react-tutorial > react-script ...

Passing Data to a Different Route in Vue.js

Being new to Vue.js, I have a question on how to efficiently handle data retrieval from my backend application. Here is the code snippet that fetches all the data: var app2 = new Vue({ delimiters: ['%%', '%%'], el: '#app2& ...

Struggling to properly parse JSON data using jQuery

I am a beginner in jquery and have a php script that returns JSON data. However, I am facing an issue while trying to fetch and process the result using jquery. Below is the code snippet: calculate: function(me, answer, res_id, soulmates) { conso ...

Align audio and video elements in HTML5 using JavaScript

I am facing a situation where I have two files - one is a video file without volume and the other is an audio file. I am trying to play both of these files using <audio> and <video> tags. My goal is to make sure that both files are ready to pla ...

The functioning of JavaScript's ajax capabilities

Need some help with a coding issue I'm facing. Can anyone provide suggestions for improving my code? I've come across a situation where the table is not updating when using a certain piece of code. However, upon further inspection, I found that ...

Is it necessary to include @types/ before each dependency in react native?

I am interested in converting my current react native application to use typescript. The instructions mention uninstalling existing dependencies and adding new ones, like so: yarn add --dev @types/jest @types/react @types/react-native @types/react-test- ...

This code is only functional on JSFiddle platform

I encountered an issue with my code recently. It seems to only work properly when tested on jsfiddle, and I can't figure out why it's not functioning correctly on codepen or when run from local files. Why is this code specific to jsfiddle? When ...

What is the best way to pass multiple row values in a form field using AngularJS to a web API?

Is it possible to insert multiple row values in an AngularJS controller using a web api? <tr ng-repeat="rt in xxtt"> <td> <input type="text" class="form-control" ng-model="rt.name" required /> </td> <td> ...