Using Multithreading and the Subscribe/Publish Methodology in JavaScript

Is it true that JavaScript does not support multithreading? I am seeking expert advice on a specific scenario.

I need to make an AJAX call and upon successful completion, trigger a set of events to update different parts of the UI simultaneously.

  • Would using a Subscribe/Publish pattern allow me to have multiple listeners for the AJAX completion event?
  • If so, how are these listeners notified when published? Is it done in a multithreaded way or one by one?

    Please suggest the best approach to achieve this. Your insights would be greatly valued.

EDIT::

I am aware that popular frameworks like JQuery support this pattern. However, I need to create this functionality from scratch due to our own framework constraints.

Answer №1

If you're looking to kickstart your project, I have a Request Pooler that could be really helpful. [Since this answer was accepted I've retired the pooler in favor of a more comprehensive "AJAX Helper" - the link has been updated.]

While it may not cover all your needs, it's a functional solution that has stood the test of time:

Depressed Press DP_AJAX

This tool allows for handling multiple requests at once with timeout/retry options, per-request handlers, and easy integration with other code.

You can set up a pool (specifying how many simultaneous requests are permitted) and send requests its way. Once they're completed, they trigger the specified handler function.

Here's a simple example of how it works:

// Handler function
function AddUp(Num1, Num2, Num3) {
    alert(Num1 + Num2 + Num3);
};

// Initialize the Pool
myRequestPool = new DP_RequestPool(4);

// Begin the Interval
myRequestPool.startInterval(100);

// Create the Request
myRequest = new DP_Request(
    "GET",
    "http://www.mysite.com/Add.htm",
    {"FirstNum" : 5, "SecondNum" : 10},
    AddUp,
    [7,13]);

// Add the request to the queue
myRequestPool.addRequest(myRequest);

This tool is open source, so you're welcome to modify it as needed.

Jim Davis

Answer №2

I came across an informative article that delves into the topic you are exploring in depth. It suggests creating a JavaScript file with an array to store handlers/subscribers. Each subscriber then adds itself to this array. When it's time to close your Ajax call, a function is called which loops through each subscriber and notifies them individually:

this.subscribers = [];
...
 for(var i = 0; i < this.subscribers.length; i++)
  {
    this.subscribers[i].notifyHandler.call(this, eventArguments);
 }
...

Answer №3

Can this function as a lightweight system for passing messages between components?

function CustomMessenger() {
    this.MessageQueues = {};

    this.PostMessage = function (Subject) {
        var Queue = this.MessageQueues[Subject];
        if (Queue) return function() {
                                        var i = Queue.length - 1;
                                        do Queue[i]();
                                        while (i--);
                                    }
        }

    this.Listen = function (Subject, Listener) {
        var Queue = this.MessageQueues[Subject] || [];
        (this.MessageQueues[Subject] = Queue).push(Listener);
    }
}

you can use it like this:

var messenger = new CustomMessenger();
messenger.Listen("some message", callback());
messenger.Listen("some other message", anotherCallback());
messenger.Listen("some message", yesAnotherCallback());

and later:

messenger.PostMessage("some message");

will dispatch the stored messages

Answer №4

It is highly recommended to utilize a library for this task in order to prevent any browser compatibility issues. One popular option is jQuery, which offers Ajax capabilities allowing you to run code upon completion of the call. You can refer to the documentation here for more information.

Answer №5

To run functions simultaneously, follow this method:

this.functionsToRun = [];
...
 for(var j = 0; j < this.functionsToRun.length; j++)
  {
    setTimeout(function(){this.functionsToRun[j].runFunction.call(this, args);},0);
 }
...

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

Client-side Results in Meteor.http.call Return Undefined

Using the Mashape Airbnb API: The code below can be found in the Clients->airbnb.js file. I am encountering undefined results when running it. However, the same API works perfectly fine in this jsFiddle demo. function getListings(place) { alert(pla ...

Encountered an unexpected identifier error while executing a Nuxt.js project

I am utilizing the following technologies: Node.js version 6.14.2 NPM version 6.0.1 Ubuntu 16.04 Whenever I attempt to execute a project, I encounter the following error message: npm run dev node_modules/nuxt/lib/core/module.js:14 async ready( ...

Struggling to get JavaScript to successfully load a .txt file in order to load various links

I created a cool feature that takes users to a random link, but I currently have a large list of links and wanted to find a way for JavaScript to read them from a text file. The code I have tried so far is not working, and I have experimented with other s ...

Can a wasm file be registered in a similar way to a JavaScript file?

My JavaScript file is calling a WebAssembly (wasm) file, but it is fetching the file from the wrong location when I register the script in a specific part of the code. To address this issue, what is considered the best practice? Here's the current s ...

Reorganizing Elements within an Array using JavaScript

Imagine I have the characters: H, M, L I want to create sorted arrays like this: var array1 = [ "H", "M", "L", "L", "M", "H" ]; My goal is to avoid having more than one unique character in the first three and last three characters when using the shuffl ...

"Eliminate a specified range of characters from a string using JavaScript

I am currently working on a JavaScript function that will remove specific characters from a string. I have tried various methods such as `string.slice()`, `string.substr()`, and `string.substring()`, but what I really need to do is remove everything before ...

Retrieving a map using latitude and longitude coordinates saved in a database

I have a webpage with an embedded Google Map and a dropdown list of cities. The latitude and longitude values for each city are stored in a database. When a user selects a city from the dropdown list and clicks submit, I want the map to load with the corre ...

Instructions for printing a page and closing the Print window using Selenium

New to using Selenium: I tried the following code in Selenium to open the print window, but unfortunately it doesn't seem to work Keyboard keyboard = ((HasInputDevices)driver).getKeyboard(); keyboard.pressKey(Keys.ENTER); keyboard.pressKey(Keys.ch ...

Validation of VAT numbers using JavaScript instead of PHP

I came across an interesting function at this link that is used for checking VAT numbers in the EU. However, I am struggling to integrate it with my registration form. I would like to convert it into a JavaScript function so that I can validate the number ...

Experiencing a strange response while attempting to parse the result of an Angular 2 HTTP JSON request

After successfully implementing the http.get call and retrieving data from the request, I encountered an issue: this.http.get('https://data.cityofnewyork.us/resource/xx67-kt59.json').subscribe(data => { // Read the result field from the ...

What is the process for accessing and modifying cookies in a local file:/// HTML document?

What is the most effective method for reading/writing cookies in a local file:/// HTML document using JavaScript or jQuery? I attempted the following: function setCookie(c_name, value, exdays) { var exdate = new Date(); exdate.setDate(exdate.getDate( ...

Incorporating a series of image links into a Three.js project with the addition of a

My latest project involves creating a reflection cube with randomly changing images on each side every time the site is reloaded. Here is the code I have written: var imgAr = [ 'sources/instagram2/image1.jpg', 'sources/instagram2/image2.jp ...

How do I fix TypeError: req.flash is not a valid function?

While working with user registration on a website, validation is implemented using mongoose models and an attempt is made to use Flash to display error messages in the form. However, in my Node.js app, an error is occurring: TypeError: req.flash is not ...

Transferring class titles between div elements

I would like to implement a feature where class names on div elements shift after a brief delay, perhaps 10 seconds. My goal is for the 3 classes listed below to cycle through the div elements and start over once it reaches the last one. For instance: & ...

What is the optimal value for the variable x in this scenario?

What is the correct value for X to make this condition valid? // Your code goes here if (x == 1 && x === 2) { console.log('Success!'); } ...

Displaying an iframe in Internet Explorer

My current setup involves a button that triggers the loading and printing of a report within an "invisible" iframe enclosed in a div. This process allows users to print the report from a different page without any visual disruption or changing pages, aside ...

Obtain the specific key's value from a new Map state

In my code, I've defined a variable called checkedItems as a new Map(); When I try to console.log(checkedItem), the output is as follows: Map(3) {"1" => true, "1.5" => true, "2" => false} Is there a way ...

Error: JSON parsing stopped due to unexpected end of file while attempting to parse data

After testing with other APIs successfully, I found that this particular one is not functioning as expected. const express = require("express"); const https = require("https"); const bodyParser = require("body-parser"); const ...

Create div elements using JSX and add them to an array

I am working with a structure that looks like this: var circle = { 'one': {items: []}, 'two': {items: []}, 'three': {items: []}, 'four': {items: []} }; Each items array needs to contain 10 unique ...

The use of dangerouslySetInnerHTML in a React application is causing issues when trying to include Segment.io tags

Currently, I'm integrating Segment.io into my react/NextJS application. I'm mimicking the pattern established by a previous function that deals with Google Analytics const segmentWriteKey = 'xyz'; export default class CustomDocument ...