Stop the old $http request that has been running longer from responding after the newest request

Recently encountered a puzzling situation and couldn't find a solution even after thorough searching.

I have a textbox where users can enter keywords to filter table data. The input element has an ng-change directive triggering the following code:

return $http.get(url).then(function (response) {
    return response.data;
});

Everything was working smoothly until our tester discovered some unexpected behavior in IE11. For example, typing "M-A-T-T" in the textbox in IE10 resulted in:

https://i.sstatic.net/n5D2c.png

Subsequent requests took longer than the first, with the fourth request being the one received by the controller.

Typing "M-A-T-T" in the same textbox in IE11, on the other hand, showed:

https://i.sstatic.net/HGZLT.png

Inexplicably, the second request would take nearly 2 seconds to complete after the fourth request, causing the wrong results to be displayed. How can this issue be addressed in Angular? Thank you for any insights.

UPDATE Following frosty's suggestion, I've implemented the following additional function which works well:

var cancelDeferred;

var getUsers = function (criteria) {
    if (cancelDeferred) {
        cancelDeferred.resolve();
    }
    cancelDeferred = $q.defer();
    return $http.get(url, { timeout: cancelDeferred.promise }).then(function (response) {
        cancelDeferred = undefined;
        return response.data;
    });
};

The primary challenge was handling errors when utilizing this method. Timeouts generated error responses similar to HTTP 500 errors. To handle actual errors while ignoring timeouts:

function onError(data, status) {
    if (data.data !== null && data.status !== 0) {
        //handle error
    }
}

Looking into implementing global timeout handling instead of modifying numerous $http.get() calls...

Answer №1

When using $http in AngularJS, you can pass a config object as the second argument to the $http.get call. This config object allows you to specify properties such as "timeout", which can be set as a Promise. If you resolve this promise before the response is received, it will abort the request. More information on this can be found in the documentation.

It is recommended to use the "timeout" property even when using debounce to ensure the request can be aborted if needed.

To implement this, you would include something like the following code snippet:

var cancelDeferred;
function makeRequest(){
    if(cancelDeferred) cancelDeferred.resolve(); //abort previous request
    cancelDeferred = $q.defer();
    return $http.get(url,{timeout:cancelDeferred.promise})
        .then(function(res){
            cancelDeferred = undefined;
            return res;
        });
}

In this function, a promise is passed to the .get request within the config object as the "timeout" property. Resolving this deferred before receiving the response will result in aborting the request.

Find out more here

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

A Guide to Handling Errors while Converting a Map to a Promise in Typescript

I am attempting to capture errors if any of the asynchronous code within my map function fails. It seems to enter the error block but does not log anything, as the error variable remains null. Is there an alternative method for handling errors within map ...

Steps to reveal a div when a button is clicked within a v-for loop using VueJS

Context In my code, I am utilizing a v-for loop to display sets of buttons and corresponding input fields. Each button is supposed to trigger the display of its respective input field upon being clicked. Issue However, the problem arises when the button ...

Unique Tags and Javascript: A customized approach

In the process of developing a web application, I am aiming for high standardization. To achieve this goal, I plan to utilize custom namespace tags that will be modified by JavaScript based on their functionality. For instance: <script type="text/java ...

javascript/AngularJS - make elements gradually disappear

I need help implementing a fade effect for an icon in the middle of a picture that indicates scrollability to the user. Currently, when the user scrolls, I can hide the icon but would like to add a nice smooth fade-out effect. Here is the HTML code snippe ...

Steps for creating a CodeBlock in a Next.js Website blog similar to the one in the provided image

Learn how to insert a code block in Next.js. def greet(name): """ This function greets the person passed in as a parameter. """ print("Hello, " + name + ". Good morning!") Here is an example of ...

Guidelines for utilizing regex to match this specific string

Hey guys, I need help with parsing this string (a url). example.html/#playYouTubeVideo=id[lBs8jPDPveg]&width[160]&height[90] I'm trying to extract the values for id, width, and height within brackets. This is what I've come up with: [ ...

Finding out which carousel the user is currently engaging with in the Slick Carousel can be accomplished by following these steps

I am struggling with applying a class to the carousel container when the first slide is active in a page that contains multiple Slick carousels. Is there a way to update the code below so that the class is only applied to the specific carousel the user is ...

Ways to have a div show up and stay in place as you scroll down?

How can I make the div "full" sticky after scrolling down 200px, and revert to display none when scrolling back up? Is there a way to accomplish this using JavaScript? In the code snippet below, you will find three divs: header, header2, and header3. The ...

What is the best way to initiate a function from within another function while working with ReactJS?

Seeking guidance on how to trigger a Redux state change by calling a function from another function using the onClick event. Currently, I am able to invoke the Jammingmenu upon clicking an icon, however, no action is performed or alert displayed. Any assis ...

AngularJS encountered an error: $http.get 405 (Method Not Allowed)

Whenever I receive a request from a URL like this: $http({ method: 'GET', url:'http://mooc-lms.dev.web.nd/v0.3/users/login' }).success(function(data, status, headers, config) { //code }); An error ...

Determine all checkboxes in a table that are selected if the rows contain a display style tag using Javascript

Currently, I have a basic text filter that assigns a display property to rows in a table either as "none" or "table-row". My challenge lies in trying to modify my "select all" script so that it only interacts with the checkboxes that are visible on the pag ...

Modifying the order of Vuetify CSS in webpack build process

While developing a web app using Vue (3.1.3) and Vuetify (1.3.8), everything appeared to be working fine initially. However, when I proceeded with the production build, I noticed that Vue was somehow changing the order of CSS. The issue specifically revol ...

Tips for personalizing the color scheme of Material UI Stepper Step?

I need help customizing the disabled Step color for Material UI Steppers. The default colors are Blue for enabled steps and Grey for disabled steps, but I want to change it to a different color as shown in this example: https://i.stack.imgur.com/HGGxp.png ...

Determine the React component's position in relation to the viewport while scrolling, ideally in percentage

I'm searching for effective solutions to solve this issue that has me stumped, and haven't come across any suitable libraries. What I'm looking for specifically is a way to track a Component's vertical position (Y) when scrolling, but ...

Modify the templateURL of a directive dynamically following a successful $http.get() request

I've been experimenting with implementing 'skeleton' loading in various components of the UI. One approach I'm taking is to use a directive that initially loads a template with low opacity, resembling a mock table. Once I retrieve the n ...

Building vue js logic to manage state across multiple ul li elements

I have a situation where I have an unordered list with a static number of list items (menu elements) that are rendered on the server side. I need to add some state-based logic to each list item, such as changing the color of the active item and expanding ...

`The logo does not dim when the popup is displayed`

I'm currently experiencing an issue with pop-ups on my page - when they appear, they create a shade over all elements of the page except for my two logos and are displayed with a border around them. Here's what my page looks like before the popu ...

Uncovering the Mystery of Undefined Dom Ref Values in Vue 3 Templaterefs

I am currently experimenting with the beta version of Vue 3 and encountering an issue while trying to access a ref in the setup function. Here is my component: JS(Vue): const Child = createComponent({ setup () { let tabs = ref() console.log(t ...

Develop a Rails object using AJAX and JavaScript

Within a music application built on Rails, I am attempting to monitor plays for tracks by artists. This involves creating a unique play object each time a visitor plays a track on the site. These play objects are assigned their own distinct IDs and are ass ...

Searching for the Magic Index using Binary Search

Currently working on mastering binary search and encountering difficulties while trying to use it to locate the "magic index" within an array, where the magic index is defined as A[i] == i. While I have come across some Java implementations using recursio ...