When a newer request is made, I would like to cancel my previous one

Currently, I am working with a text box that triggers an HTTP call for each input character. However, my challenge lies in the fact that I need to be able to cancel the previous request if the user enters the next character before receiving a response.

Answer №1

If you want to achieve this, consider using the rxjs switchMap operator.

With switchMap, on each emission, the previous inner observable is canceled in favor of subscribing to a new one. This can be likened to switching to a new observable. It's especially useful for scenarios like typeaheads where the response of the previous request becomes irrelevant once a new input is received.

Here's an example:

// Implementing with RxJS v6+
import { interval, fromEvent } from 'rxjs';
import { switchMap } from 'rxjs/operators';

fromEvent(document, 'click')
  .pipe(
    // Restart counter on every click
    switchMap(() => interval(1000))
  )
  .subscribe(console.log);

This demonstration is featured on the Angular University blog, showcasing how a new request supersedes and cancels out the previous one.

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

Answer №2

Once an HTTP request is sent to the server, it cannot be canceled as expected. The server will still attempt to fulfill the request even if you disregard the response.

However, there are scenarios where a streaming HTTP request can be terminated or when using two separate HTTP requests to start and cancel a job on the server can emulate cancellation (although this involves successful completion of both requests).

If looking for alternatives, consider exploring throttling or debouncing in JavaScript. These techniques ensure that a function is only called once per keypress, based on certain conditions like not being called within a specific time frame.

[UPDATE] While some tools allow for the "cancellation" of in-flight HTTP requests (like rxjs), keep in mind that this may not prevent the server from processing the call if it has already been received. Additionally, the ability to cancel requests depends on your specific HTTP implementation. More information can be found 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

What is the best way to target and focus on all class fields that have a blank value?

<input type ="text" class="searchskill" value=""> <input type ="text" class="searchskill" value="3"> <input type ="text" class="searchskill" value=""> <input type ="text" class="searchskill" value="4"> Is there a way to target o ...

Tips for extracting the src attribute from a dynamically generated iframe

My dilemma stems from a function that generates an iframe with content on my website, which unfortunately I cannot control as it is loaded remotely. The function initially creates: <span id="myspan"></span> Once the JavaScript function fu ...

The jQuery array does not appear in the database after its data has been transferred to a PHP array in a separate file

My attempt to send values from a jQuery array to another PHP array from {file.js} to {file.php} does not seem to be working as expected. Even though the data is being transferred, it fails to appear in the database An empty row appears in the targeted colu ...

What is the best way to identify duplicate data being returned from a server within a for loop?

When receiving sorted data from the server through an infinite scroll, my goal is to filter out duplicate entries and add new unique data to a client-side array. If duplicates are found, I want to stop the infinite scrolling process. $scope.collections = ...

Fetch a list of 10 items at a time using AngularJS with Ionic framework's infinite scroll feature

I'm currently working on incorporating an ion-infinite-scroll feature using the ionic framework. My REST API allows me to set the index in order to request a specific range of data. Here's what my Service looks like, with 'begin' and &a ...

The Camera component in React Native is not currently supporting foreground service

Trying to capture images in a foreground service, such as taking pictures while the user is using another app. Everything works fine within the app, but when the app is closed with the foreground service active, the camera stops working and shows this erro ...

The desktop display is experiencing a technical issue where menus are failing to appear

When my website is opened on desktop, the state remains false which causes no menus to show. I only want this functionality to be active on mobile devices. const Navbar = () => { const [isMenuOpen, setIsMenuOpen] = useState(false); const toggle = () ...

Integrating content from a separate PHP page into the main index PHP page

I can't seem to get the #container1 div on my index.php page to load with the content from another #container2 div on page1.php. It's frustrating because I've checked my file hierarchy and everything seems correct. This is how my files are ...

It only takes half a minute for ts-node-dev to set up its watchers

Having tried both ts-node and ts-node-dev, I am frustrated by the fact that they take almost the same amount of time to start my app server. This issue has been a recurring problem for me, with no successful attempts at resolving it. Currently, I am opera ...

Position two buttons on the right side of the text

Is there a way to align two buttons on the far right side of a block of text? I want all the content to be in line, with the text on the left and the buttons on the right. While I've found solutions for aligning one button, I'm struggling to get ...

Dealing with a missing item in local storage in an Angular application

When working with local storage, I have a function that saves certain values and another method that reloads these values. However, what is the best approach to handle missing items in the local storage? This could happen if a user deletes an item or if it ...

A guide on passing an array parameter using JavaScript

I need to transfer an array of ids from one page to another. I have created the $ids variable in PHP, and I am using it with jQuery like this: var ids = <?php echo json_encode($ids); ?>; jQuery(ids).each(function() { filters.push('ids[]=&a ...

Removing a row from MySQL using JQuery Ajax

Hello there! I'm currently facing an issue while trying to remove a row from a MySQL database using PHP and AJAX. I initially thought it would be a simple task with $.ajax {}, but unfortunately, the row is not getting deleted for some reason. Here&apo ...

Errors are being encountered by npm during the execution of tsc and concurrently when running the start command

Every time I attempt to execute npm start, a series of errors pop up on my screen... 19 error node v4.2.0 20 error npm v3.10.5 21 error code ELIFECYCLE 22 error <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d1f081e180008400 ...

Automatic closure of Bootstrap alerts in an Angular 14 application

I've implemented the bootstrap alert for displaying success and failure messages. The alert box can be closed manually by clicking the "X". However, I'm struggling to find a way to automatically close the alert box after 3 seconds. Here's t ...

"Delivering dynamic HTML content using React/Redux variables in the production environment

I am currently in the process of developing a React web application, and I have encountered an issue where a variable intended to store a schedule is being filled with the HTML content of the page when I build and serve the application. Interestingly, the ...

Display a list of items using ReactJS by mapping through an array of objects and rendering based on

How can I render a set of <div> </div> based on the items in an object without having to specify their names? In the code snippet below, I want the display of WorkObjectID and WorkObjectVal to be dynamic rather than static. If I include TempOb ...

How can I retrieve the data returned by an ajax call using jQuery?

I have a function that is making an AJAX call to return data. Here is the code: function reqNodelistByField( i ) { $.ajax({ type: 'post', url: './req.nodelist.by.field.php', dataType: 'text', ...

Ways to retrieve an input field value without triggering form submission

I'm currently working on a payment form where users input the amount in a text field. I also have another text field on the same form that should automatically display the amount in words based on the user input. However, I'm struggling to figure ...

Discovering the worth in Meteor MongoDB

As someone who is new to web programming, I have been experimenting with Meteor and MongoDB lately. I have a form that sends data to MongoDB, and by using the query below, I was able to retrieve the most recent entry: database.findOne({}, {sort: {'t ...