Stop initiating the HTTP fetch() requests

Found on Stack Overflow - How can I stop an HTTP fetch() request?, it is now possible to cancel a fetch() request using AbortController.

Instead of canceling a fetch() request, I am interested in pausing it temporarily and then resuming it at a later time. Is this achievable?

Answer №1

Let's dive into the heart of your inquiry:

Is there a way to temporarily halt a fetch() request and then resume it at a later time, rather than completely canceling it?

The definitive answer is "no, this functionality is not supported."

With that in mind, in response to your additional query:

The primary scenario involves a critical event occurring that takes precedence over all other pending requests. In such cases, the other requests should be put on hold until the urgent task is completed.

One potential solution could be to create a priority queue system (manually or through a third-party library, beyond the scope of this discussion) where your application manages the outcome of the resolved fetch promise only after addressing any higher-priority tasks.

Answer №2

In order to halt and continue an HTTP request from JavaScript methods, aside from the AbortController, there are a few approaches you can take.

i) One method involves using the fetch() call within a promise, allowing you to choose whether to reject or resolve the request based on whether you wish to pause or reject it. However, this approach does not support the ability to resume the request.

ii) The AbortController can be used to achieve a similar functionality by pausing requests (aborting the ongoing request) and then resuming the requests again using the same controller.

const controller = new AbortController();
const signal = controller.signal;    
fetch(url, {..., signal: signal}).then(response => ...);

To pause:

controller.abort() 

To resume:

fetch(url, {..., signal: signal}).then(response => ...);
Essentially, this involves making another request using the same controller object.

For more information, you can refer to: https://developer.mozilla.org/en-US/docs/Web/API/AbortController

iii) If you are interested in pausing/resuming stream processing through HTTP, you can refer to the following sample method I discovered: https://gist.github.com/Grigore147/4611134

var Http = require('http');
var Fs   = require('fs');

// Provide a URL to a large video file
var url = 'url';
var path = 'save_path';

var downloaded = 0;
var percents = 0;
var size = 0;

var request = Http.request(url, function(response) {
  size = parseInt(response.headers['content-length']);
  
  response.on('data', function(chunk) {
    downloaded += chunk.length;
    percents = parseInt((downloaded / size) * 100);
    
    console.log(percents +'%', downloaded +'/'+size);
  });
  
  response.on('error', function(error) {
    console.log(error);
  });
  
  response.pipe(Fs.createWriteStream(path));
  
  setTimeout(function() {
    response.pause(); console.log('stream paused');
    
    setTimeout(function() {
      response.resume(); console.log('stream resumed');
    }, 5000);
  }, 5000);
}).end();

Answer №3

Halting a fetch() operation is not achievable. The purpose of the AbortController is to terminate, not to pause. And since termination is final, there is no option to resume. It's akin to severing a string with a blade. In this analogy, Cancel == cut.

Therefore, various alternative methods can be explored:

  1. Dividing a large request into several smaller ones
  2. Implementing the Range header to fetch multiple segments, with the requirement that the joining process and header support are on your end
  3. Researching the applicability of ReadableStream in this scenario (although it may be a long shot)
  4. appears to offer a potential solution as well ;)

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

Create your own AngularJS directive for displaying or hiding elements using ng-show/ng

Caution: Angular rookie in action. I'm attempting to craft a personalized widget that initially displays a "Reply" link, and upon clicking it, should hide the link and reveal a textarea. Here's my current progress, but unfortunately, it's n ...

The expected React component's generic type was 0 arguments, however, it received 1 argument

type TCommonField = { label?: string, dataKey?: string, required?: boolean, loading?: boolean, placeholder?: string, getListOptionsPromissoryCallback?: unknown, listingPromissoryOptions?: unknown, renderOption?: unknown, getOptionLabelFor ...

Visual UpdatePanel control layout in a SharePoint web part using AJAX with C#

I'm currently developing a SharePoint web part in C# and incorporating an UpdatePanel for AJAX functionality. The implementation is functioning correctly, but I am seeking guidance on structuring the visual layout of my controls (without the aid of Sh ...

Utilize prop-types inheritance when a component is rendered via props

Is it possible to inherit prop-types when a component is rendered via the parents prop, without direct access to 'ChildProps' and 'Props' interface? Parent Component interface ChildProps { counter: number; setCounter: React.Dispat ...

Exploring the testing capabilities of Angular JS in conjunction with third-party libraries such as

When testing an angular controller that utilizes an external library like Google Analytics event tracking, how can you approach it? For instance: $scope.showVolumn = function() { ga('send', { 'hitType': 'event', ...

Is there a method to refresh the entire DOM-based location without having to reload the browser window?

Is it possible to achieve smooth asynchronous page transitions without breaking existing JavaScript animations in a system like Webflow? I'm struggling to find a way to present new elements to the DOM without disrupting the animations that are already ...

Combining two arrays of names and values into a fresh object using Javascript

Trying to merge two arrays, one for column headers: cNames = ["Year","Count"] And another for data: mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143] The goal is to combine them like this: [ { Year: "2005", Count: 5021 ...

Extract a section of the table

I'm looking to copy an HTML table to the clipboard, but I only want to include the rows and not the header row. Here is the structure of the table: <table style="width:100%" #table> <tr> <th class="border"></th> ...

Linking states using AngularJS and jQuery

Imagine I have a scenario with two different states: .state('page1', { url: '/page1', templateUrl: 'pages/templates/page1.html', controller: 'page1' }) .state('page2', { url: '/page2& ...

Assess the scss styles specific to components following the global min.css in a React application

ISSUE Imagine we have a min.css file that needs to be imported globally: index.js import ReactDOM from "react-dom"; import App from "src/App"; import "library/library.min.css"; ReactDOM.render(<App />, document.getE ...

What is preventing the input box from shrinking further?

I created a search box using CSS grid that is supposed to shrink when the page is resized. However, it doesn't seem to shrink as much as I expected it to. Here is how it appears when fully extended: https://i.stack.imgur.com/tPuCg.png And here is how ...

Utilizing 'Ng-If' causes a glitch in the program during the execution of a $( '#x' ).change event or when adding a new item with AngularFire $add

After implementing ng-if in my code, I observed two specific instances where it caused unexpected behavior. The first instance involves using ng-if="isOwnProfile" for an image-upload toolbar. However, the use of ng-if resulted in the event listener ceasin ...

The class .is-invalid transforms into .is-valid when rendered

Currently, I am incorporating bootstrap into my react project. In this case, I have a variable called mobile that needs to undergo validation whenever there is a change in the input field. Below is the code snippet for the component: const EnterMobile = ( ...

How can you modify Jquery show_hide so that the page automatically scrolls to the bottom of the concealed field when the button is clicked?

On my website, there is a button that reveals a map when clicked. The button is visible when the page loads, but once clicked, the map slides open and goes out of sight since the page loads at the top as usual. My goal is to have the page automatically scr ...

Allow users to zoom in and out on a specific section of the website similar to how it works on Google Maps

I am looking to implement a feature on my website similar to Google Maps. I want the top bar and side bars to remain fixed regardless of scrolling, whether using the normal scroll wheel or CTRL + scroll wheel. However, I would like the central part of the ...

Exploring the potential of utilizing records within deepstream.io

Lately, I've been delving into the world of records and I find myself pondering on the practical limitations when it comes to the size of a json structure. Is there a recommended maximum length? Can you store an entire chat history as an (anonymous) r ...

Having trouble linking the component to the Redux store

I've been encountering difficulties connecting my CMSForm component to the Redux store. Below are the snippets of code that I have implemented: Reducer: const cmsDefaultState = { cmsNum: "", facilityName: "" }; export default (state = cmsDefault ...

Maximizing the potential of .delegate in combination with .closest

$('.inputRadio').parent().click(function (e) { //implement delegate method here }); Looking for assistance on how to integrate the delegate method in the provided function. Any suggestions? ...

Create a dynamic image showcase using PHP or JavaScript

So I have a large collection of car photos organized in a structure similar to this (this is just a fictional example to illustrate my idea): Cars > Audi > Sports cars > '5 pictures' Cars > Audi > Family cars > '3 pictur ...

Tips for displaying user-entered information from a form after submitting it with PHP

How can I display the email in the email text input field with this code? It doesn't seem to work correctly when there is a failed login attempt. value= "if(isset($_POST['submit'])){ ?PHP echo $_POST[''email']?>"; ...