Most effective method for delaying ajax call/xhr requests

I am having trouble phrasing my question correctly, but I have included the code below. Essentially, I want to make an ajax request, check the callback, and continue to perform the ajax request until it receives the desired response (in this case, connectedvoter equals 1).

The issue I'm facing is that the process happens very quickly, taking only about 80ms, and the number of xhr's increases rapidly at this speed. I have tried various methods to 'pause' the process, but all options I could think of seem to consume a lot of CPU.

Is there a way to slow down the frequency of requests made, perhaps to once every second or two, without using up too much CPU?

var connctedvoter = 0;
var govoters = function () {
        $.ajaxSetup({
            async: false
        });
        var url = "getconnectedvoter.php";
        var data = {
            userid: userid
        };
        $.getJSON(url, data, callback);
    };
var pausevoters = function () {
        console.log("pausing ajax voters");
    };
var callback = function (response) {
       if (response.error) {
            return;
        }
        if (response.connectedvoter == 0) {
            setTimeout(govoters, 150);
        } else {
            $('#vanid').html(response.vanid);
            $('#name').html(response.name);
            $("#mapurl").attr("src", response.mapurl);
            $('.call').fadeIn();
            return;
        }
    };

//DO THIS TO START
setTimeout(govoters, 150);
pausevoters();

Answer №1

To improve the functionality, adjust the delay for the timeout as follows:

if(!response.connectedvoter) {
  setTimeout(govoters, 2000); // now set to 2000 instead of 150
}

Rather than making 10 requests per second:

setTimeout(govoters, 150); // this sets one request every 150 milliseconds.

You can start by changing this code snippet from:

//INITIATE WITH A TIMEOUT
setTimeout(govoters, 150);

To simply calling the function like this:

//INITIATE WITHOUT A TIMEOUT
govoters();

The use of a timeout may not be necessary in this case.

Answer №2

If you want to update the timing of the function call, simply replace the following line in your code:

setTimeout(govoters, 150);

Change it to:

setTimeout(govoters, 1000); // Now delayed by 1 second

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

Error: Encountered an unexpected token F while trying to make a POST request using $http.post and Restangular

In our current project, we are utilizing Angular and making API calls with Restangular. Recently, I encountered an error while trying to do a POST request to a specific endpoint. The POST call looked like this: Restangular.one('aaa').post(&apos ...

What could be causing the appearance of 'undefined' while attempting to implement the useState hook in React?

I'm currently working on incorporating the useState hook in React to set an initial value as an empty function. Nevertheless, when attempting to retrieve and output the state variable using console.log, it returns undefined. This is the code snippet ...

Circular dial progress bar with dynamic data loading

I am currently experimenting with Knob and AJAX. The issue I'm facing is that although the number inside changes in real time, the progress bar remains static. You can view the project here: www.skincannon.com The code snippet is as follows: HTML: ...

I am looking to send data to an API whenever the user closes the browser tab

Hey guys, I need some help with a problem I'm facing in my current scenario. I am working on a feature to lock bookings for other admins, and I have created a field in the bookings table to store the admin's ID when they access the booking. Howev ...

"Use jQuery to toggle the slide effect for the first element of a

Below is the HTML code snippet: <div class="row header collapse"> Content 1 <i class="fas fa-chevron-circle-up" ></i> </div> <div class="instructions-container"> <div></di ...

How can a controller be used to access and modify data from various partials?

I need assistance with handling multiple ng-models spread across 2 partial HTML files. Here is the content of partial1.html: <input ng-model="A" /> //user input for A <input ng-model="B" /> //user input for B <input ng-model="C" /> //us ...

Modify picture properties when listbox is altered using jQuery

I need to set up a unique album gallery display where different folders are selected based on the item chosen in a selectbox. Below is the HTML code: <select name="album" id="album" onChange="changeimage();"> <option value="0" selected disab ...

Galleriffic 2.0: Enhancing Animation Queues

I'm currently exploring how to utilize the stop() function in order to halt the animation buildup within Galleriffic. This issue arises when swiftly and repeatedly mousing over the thumbnail images. While I understand that in a basic jQuery script, yo ...

Is it possible for Typescript to resolve a json file?

Is it possible to import a JSON file without specifying the extension in typescript? For instance, if I have a file named file.json, and this is my TypeScript code: import jsonData from './file'. However, I am encountering an error: [ts] Cannot ...

Securing RESTful APIs with stringent security measures

Lately, I've been delving into using modern front end technologies such as React and Angular. This has led me to explore tools like JSON Server for simulating restful database interactions. I've noticed that most REST APIs require authentication ...

The image selection triggers the appearance of an icon

In my current project, I am working on implementing an icon that appears when selecting an image. The icon is currently positioned next to the beige image, but I am facing difficulties in making it disappear when no image is selected. Below are some image ...

JavaScript code to activate a text box when a checkbox is clicked

I have a dynamic table that is generated by JavaScript based on the selected item from a dropdown list. The table consists of a column for checkboxes, a column for displaying names, and a column for inputting quantities. I would like to have all textboxes ...

How can the application configuration be sent from MVC to Angular 2?

Looking to upgrade from RC4 => Angular 2.1.0 let element = this.elementRef.nativeElement; let myattr = element.getAttribute("applicationConfig"); Encountering the error: Error: Call to Node module failed with issue: TypeError: native.getAttribute i ...

Is there an obstacle hindering the load event?

There's something strange happening on a website I created. The page content loads in 5 or 6 seconds, but the DOMContentLoaded and Load Event don't actually fire until 1 minute and 10 seconds later. When I reload the page during loading, it load ...

Transmitting real-time updates from Server to Client through Ajax communication

Currently, I am utilizing an UpdatePanel to trigger a button click event that saves over 100 files to a specific folder. My goal is to have the server inform the client about the status and count of files being saved. protected void btnSave_Click(...){ ...

Sending information to a subpage through props using a query in the URL triggers a 431 Request Header Fields Too Large error

I have a page called campaigns, and I am facing an issue on the index page where I want to pass data to my dynamic page [campaignId].tsx. Although I can see the data on my dynamic page, the URL links are becoming too long, leading to an HTTP Status code 4 ...

ASP.NET MVC controller encountering internal server error 500 during Ajax request

I have a scenario where I need to populate two dropdowns in a view: <select class="input-sm form-control input-s-sm inline" onchange="loadCities()" id="comboState"> ... </select> <select class="input-sm form-control input-s-sm inline" ...

unable to inherit from THREE.js superclass

I am brand new to working with three.js and JavaScript, so I'm not sure if my issue lies within three.js or JavaScript itself. I've been trying to inherit from the THREE.Mesh class in order to display a mesh on the screen, but I can't seem t ...

Tips for modifying the main color of the React integrated Bootstrap

Currently, I am utilizing React's built-in Bootstrap (the version that doesn't require any additional library or package installation) for my website. I'm looking to customize the primary color - any suggestions on how to go about this? ...

What is the best way to ensure changes to an item in a Model array are reflected across different scopes?

I am dealing with a scenario where I have both a parent $scope and a child $scope. When the child view loads, I initiate a GET request to fetch JSON data (an array containing hundreds of objects). This data is then passed to the parent $scope. Within the ...