What is the best way to manage the maximum number of concurrent AJAX requests?

I am currently working on an autocomplete search bar feature.

<input type="text" class="form-control" id="text" >

<script>
    $("input").keyup(function(){
        let key = $("input").val();

        $.ajax({
            url: '/search',
            type: 'POST',
            contentType: "application/json",
            data: JSON.stringify({key}),
            success: function(data){
                console.log("SUCCESS")
            }
        });
    });

</script>

As users input text into the search box, I aim to send each keystroke to the backend server for suggesting results. However, this quickly triggers the maximum of 6 concurrent AJAX requests. How can I address this issue?

Answer №1

Do you wish to a) halt any ongoing request once a new one is initiated:

let inProgress;
$("input").keyup(function(){
    let key = $("input").val();
    if (inProgress) {
        inProgress.abort();
    }
    inProgress = $.ajax({
        url: '/search',
        type: 'POST',
        contentType: "application/json",
        data: JSON.stringify({key}),
        success: function(data){
            console.log("SUCCESS")
        }
    });
});

and b) delay the requests, so it only triggers autocomplete after a brief pause in typing (e.g., 500ms after the last keyup event):

let inProgress;
let debounceTimer;
$("input").keyup(function(){
    let key = $("input").val();
    if (inProgress) {
        inProgress.abort();
    }
    if (debounceTimer) {
        clearTimeout(debounceTimer);
    }
    debounceTimer = setTimeout(() => {
        inProgress = $.ajax({
            url: '/search',
            type: 'POST',
            contentType: "application/json",
            data: JSON.stringify({key}),
            success: function(data){
                console.log("SUCCESS")
            }
        });
    }, 500);
});

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

Ways to update a component's state by clicking a button located on a different component

Seeking help with changing a parent state value when clicking a button. Although there are numerous similar queries out there, I'm really struggling to grasp the concept. I've attempted lifting the state up but haven't quite nailed it yet. ...

Having trouble making an ajax request using Cordova?

I recently started a new project and included some code for making a request. Below is how my JavaScript file looks: (function () { "use strict"; document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false ); function onDeviceR ...

jQuery code unable to alter the class of a div

Need help with a script on my single page site that adds a "read more" style link to a content area's div. The goal is for the button to change the class of the content area when clicked, showing all of the content. Clicking again should hide the cont ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

Discover how to efficiently load and display a JSON array or object using JavaScript

I am new to learning about json and d3, having just started a few hours ago. While I have basic knowledge of javascript, I need help with loading a json file and displaying all the arrays and objects on the console using d3. I tried to do it myself but unf ...

Data structures of advanced complexity within HTML data attributes

I am delighted by the existence of the html5 data attribute. It's great to be able to input a plain string into html attributes and retrieve them using jquery. However, wouldn't it be wonderful to have more than just a basic string? Is there a ...

jQuery: changing the order of list elements with the eq method

I've been tackling a challenge with designing a navigation bar that consists of 3 items. The goal is to have the clicked item move to the center position on the horizontal navbar while re-arranging the order. Here's the code snippet I've com ...

Encountering an Unhandled Reference Issue while Using JavaScript and AJAX

This is a td element I created using JavaScript: '<td contenteditable="true" onBlur="saveToDatabase(this,s1,' + d.pid + ')" onClick="showEdit(this);">' + d.s1+ '</td>' + I need to pass the value of the saveToData ...

Encountering a problem when utilizing window.ethereum in Next Js paired with ether JS

Experiencing some difficulties while utilizing the window.ethereum in the latest version of NextJs. Everything was functioning smoothly with NextJs 12, but after upgrading to NextJs 13, this error started popping up. Are there any alternative solutions ava ...

The fading effects are not functioning as expected in the following code

Hey there, I'm not the most tech-savvy person, but I managed to come up with this code for page redirection. Unfortunately, I couldn't quite get the fade out and fade in effects to work properly when executing it. If anyone out there can help me ...

Is it possible to edit the HTML DOM of an external URL that is opened using window.open?

Imagine a scenario where I have a page located at: www.mydomain.com When a user clicks on a button, it triggers the opening of a new window using: newWin = window.open("https://www.otherdomain.com","a","height=800,width=1000"); Now, my objective is to m ...

Tips for implementing two Secondary Actions in React Material UI, with one positioned on the left corner and the other on the right, while ensuring that the behavior of the

Is there a way to display two secondary actions on either end of a list item without triggering additional onclick events? The placement can be adjusted by overriding the CSS properties right and left. https://i.stack.imgur.com/rhr7N.gif The issue arises ...

Issue found: React-Redux action is not being dispatched

I'm currently working on setting up Google authentication in my React Next.js application. The process involves sending the access token to my backend, where it is validated before a new token is returned in the header for accessing protected resource ...

Having difficulty updating an angular variable within a callback function

Currently, I am utilizing the Google Maps directions service to determine the estimated travel time. this.mapsAPILoader.load().then(() => { const p1 = new google.maps.LatLng(50.926217, 5.342043); const p2 = new google.maps.LatLng(50.940525, 5.35362 ...

Guide to seamlessly integrating additional validation techniques into the Magento checkout process

Is there a way to prevent customers from entering PO Boxes in the shipping address for certain Shipping Methods, such as UPS, without modifying core files like js/prototype/validation.js? I want to avoid forking such a key file. I am wondering if it is po ...

What is the best way to leverage multiple random YouTube v3 API keys simultaneously?

I have the following code snippet and I am looking to randomly select an API key from a list of keys: function search() { // Clear Results $('#results').html(''); $('#buttons').html(''); // Get Form Input ...

Issues encountered with asp.net javascript function not executing

Having trouble getting a javascript function to execute via jquery in an asp.net setting. Despite trying various approaches, the function doesn't run upon clicking the button. I've experimented with omitting jquery and using a static html input c ...

Is there a method to refresh the image in the template?

I am currently working on generating various images using canvas. Is there a way to display these images in real-time on my main.pug template without having to reload the page every time an image changes? const Canvas = require('canvas') , Ima ...

When attempting to ajax post JSON data, I received a null response as well

I have attempted numerous times to implement the code below, but I keep receiving a null value. var cartViewModel = []; $(":text").each(function (i) { var quantity = parseInt($(this).val()); var id = parseInt($(this).data ...

How can you interact between a parent's named controller and JavaScript files in AngularJS?

Lately, I've been exploring the use of named controllers in my code and find it to be a much better alternative to using traditional $scope variables. It makes accessing parent controller attributes and functions within the DOM seamless. See an exampl ...