emulating the behavior of a synchronous XmlHttpRequest

While I have taken the time to explore similar questions like Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript, I want to ensure that I consider all potential solutions.

Is it feasible to "transform" an asynchronous XmlHttpRequest into a pseudo-synchronous one by utilizing setInterval or setTimeout? My thought is that, upon successful completion of the Ajax request, a variable could be set to trigger a while loop (which has invoked either setInterval or setTimeout) along with a corresponding callback function to terminate. Am I misinterpreting the capabilities and limitations of setInterval and/or setTimeout?

Answer №1

Avoid using setInterval and setTimeout as described in your approach. Instead, focus on utilizing nested functions to write code in a more synchronous manner.

For instance:

XHR.get(your_data, function()
   {
      // Write your code synchronously here
   });

While you may use setInterval and/or setTimeout for polling a success code, it is not recommended. This method has drawbacks such as increased latency, high CPU usage, and limited scalability with multiple XHR requests.

XHR will execute your function upon completion, therefore repeatedly checking "Are we done yet?" is unnecessary. However, if there is specific behavior that needs to wait for the response (like an animation dependent on the data), you can include blocking code within an if statement:

var tick = window.setTimeout(tock, 20);
var tock = function()
{
   if (response_done)
   {
      // Execute dependent code
   }
   tick = window.setTimeout(tock, 20);
}
XHR.get(your_data, function() { /*Handle response*/ response_done = true; });

Answer №2

Understanding your query, you can create a similar outcome by implementing the code below:

var updateInterval =
    window.setInterval(function() {
        // perform an update cycle, simulating a while loop
    }, 100);

$.get('http://example.com/areWeThereYet', function() {
    // stop the intervals (simulation of the loop)
    window.clearInterval(updateInterval);
});

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

Rails application experiencing difficulties in displaying the Raty JS plugin

Encountering issues with the raty js plugin while working on Rails version 5.0. jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761 Uncaught ReferenceError: jQuery is not defined at jquery.raty.self-628421be ...

Ways to verify when leaving the webpage

After spending an excessive amount of time searching for this information, I finally figured it out. So here you have it, I'm sharing the steps to create a custom "ARE YOU SURE YOU WANT TO LEAVE THIS PAGE?" dialog. ...

Is there a cutting-edge javascript/jquery tool that enables SQL-type queries on JSON datasets?

About a year ago, this question was posed on Stack Overflow. After searching extensively for answers, it seems that all the libraries I've come across have not been updated in over a year. I'm curious if anyone knows of any currently maintained l ...

Looping the jQuery Ajax success function

Utilizing Ajax to input an array of data into a database. At the moment, when clicking on "#bookingbutton," it triggers a return block of HTML containing the ".select-room-button" button. I have incorporated the code for ".select-room-button" within the ...

Expanding Material Ui menu to occupy the entire width of the page

I'm encountering an issue with a menu I created where I can't seem to adjust its height and width properly. It seems to be taking up the full width of the page. import React, { Component } from "react"; import Menu from "@material-ui/core/Menu"; ...

Maintaining the state of Ajax pages using a URL hash

One of the pages on my website features two sets of tabs, where each tab's link is ajax-driven but also includes a proper href in case javascript is disabled. I am currently looking into implementing an ajax 'back-button' solution using a pl ...

Update the variable values in the Onclick function

I am trying to modify the onClick function attached to a button. My goal is to change the function var from 'create' to 'update' when the page loads and also through other functions. I attempted the code below but it did not work as exp ...

Geoserver does not have the 'Access-Control-Allow-Origin' header

map.on('singleclick', function (evt) { document.getElementById('info').innerHTML = "Looks like you need to redo this :) !!!"; var view = map.getView(); var viewResolution = view.getResolution(); var source = hcm.getSource(); var url = s ...

An in-depth guide on implementing debounce functionality for `keyup` events in Vue.js

I am attempting to detect when the user begins typing and stops typing using the debounce function. I experimented with Lodash and Underscore.js. On my textArea v-on:keyup="handler($event)" handler: function(e) { ...

Is it considered poor form to use res.locals in Node.js with Express?

Is it considered bad practice to use res.locals as shown in this code example? Are there potential issues that could arise from using it in this manner? app.use((req, res, next) => { const session = req.cookies.session if (session) { db. ...

What is the best way to find the most commonly used category for a product in a MongoDB collection?

I've been diving into MongoDB and encountered a challenge with my current task. I'm trying to figure out how to determine the most frequently used category in a collection. According to this JSON, the most used category is CIES. My goal is to dis ...

Encountering a Null Pointer Exception when trying to locate an element on an AngularJS website using Selenium

Testing an AngularJS website with Selenium can be challenging due to angular directives, as mentioned in a blog. Despite encountering some stability issues such as failures and exceptions like "unable to locate Element," "No such element," or "Null pointer ...

React Router v6 is throwing an error stating that within the <Routes> component, all children must be either a <Route> or <React.Fragment>

While the code snippet below may have worked perfectly fine in React Router v5, it's causing an error in React Router v6. Error: [Player] is not a <Route> component. All component children of <Routes> must be a <Route> or <React ...

Setting a timeout from the frontend in the AWS apigClient can be accomplished by adjusting the

I am currently integrating the Amazon API Client Gateway into my project and I have successfully set up all the necessary requests and responses. Now, I am trying to implement a timeout feature by adding the following code snippet: apigClient.me ...

How can you use AJAX and jQuery to animate one container and fade in another when $_GET['var'] is set and new content is loaded?

There is a <table id="pickups"> located in the file /pages/home.php. By default, the file index.php includes home.php if no other page is specified. When you click on an element (logfile) in a specific column of the table, the container with the clas ...

What is the method to retrieve the selected value from a drop-down menu that is connected to JSON keys?

I am just starting to learn AngularJS and I need help with binding column names (keys from key-value pairs) to a select list. I want to be able to retrieve the key name when the selection in the select list is changed. The select list displays: name, snip ...

The Redux store has been modified, yet the changes are not reflected in the

In my Posts.js component, I am mapping every object in the posts array. Within this function, I attempt to filter all notes that have the same post_id as the id of the current mapped post object and store them in a variable called filteredNotes. I then pas ...

What could be causing this highchart plot to fail to display in both IE and Chrome?

Check out the plot in this jsfiddle: http://jsfiddle.net/essennsee/y5HCm/ The plot looks good in Firefox, but only shows the legend in IE and Chrome. If I remove the following code snippet it works fine. Is there a different way to format the labels?: ...

What is the most optimal jQuery code to use?

Just wondering, which of the following code snippets is more efficient (or if neither, what would be the best way to approach this)? Background - I am working on creating a small image carousel and the code in question pertains to the controls (previous, ...