End all occurrences of XMLHttpRequest

In my code, I am calling the function SigWebRefresh at specific intervals of 50 milliseconds.

tmr = setInterval(SigWebRefresh, 50);

The function SigWebRefresh utilizes XMLHTTPRequest:

function SigWebRefresh(){   
    xhr2 = new XMLHttpRequest();    
    xhr2.open("GET", baseUri + "SigImage/0", true );
    xhr2.responseType = "blob"; 
    xhr2.onload = function (){
        var img = new Image();      
        img.src = getBlobURL(xhr2.response);        
        img.onload = function (){           
           Ctx.drawImage(img, 0, 0);
           revokeBlobURL( img.src );
           img = null;
        }
    }   
    xhr2.send(null);
}

To stop the interval set by setInterval(), I have used the clearInterval method like this:

 clearInterval(tmr);    

Although xhr2.abort(); can abort one instance of the XMLHttpRequest, I am looking for a way to abort all uncompleted XmlHttpRequest. How can I achieve this?

Answer №1

For better organization, consider adding each xhr2 variable to an array and using Array.prototype.forEach to stop each xhr2 variable.

var requests = [];

function RefreshData(){   
    xhr2 = new XMLHttpRequest();
    requests.push(xhr2);    
    xhr2.open("GET", baseUri + "DataImage/0", true );
    xhr2.responseType = "blob"; 
    xhr2.onload = function (){
        var image = new Image();      
        image.src = getBlobURL(xhr2.response);        
        image.onload = function (){           
           Ctx.drawImage(image, 0, 0);
           revokeBlobURL( image.src );
           image = null;
        }
    }   
    xhr2.send(null);
}

// Stop all requests
requests.forEach(function(req) {
  req.abort()
})

Answer №2

If you want to manage a list of processing requests, you can follow these steps:

function removeElement(array, item){
    var index = array.indexOf(item);
    if (index > -1) {
        array.splice(index, 1);
    }
}

var all_processing = [] // Store all processing requests
function UpdateRequests(){   
    var xhr = new XMLHttpRequest();    
    xhr.open("GET", baseUri + "Image/0", true );
    xhr.responseType = "blob"; 
    xhr.onload = function (){
        var img = new Image();      
        img.src = getBlobURL(xhr.response);        
        img.onload = function (){           
           Ctx.drawImage(img, 0, 0);
           revokeBlobURL( img.src );
           img = null;
           removeElement(all_processing, xhr); // Remove finished requests from the list
        }
    }   
    xhr.send(null);
    all_processing.push(xhr); // Add request to the list
}

To clear the list:

for(var i in all_processing)
    all_processing[i].abort();
all_processing = [] // Clear the list of requests

Answer №3

 let httpRequest = null;

 function RefreshSignature(){  
      if( httpRequest != null ) {
            httpRequest.abort();
            httpRequest = null;
      }
      httpRequest = new XMLHttpRequest();    
      httpRequest.open("GET", baseURL + "SignImage/0", true );
      httpRequest.responseType = "blob"; 
      httpRequest.onload = function (){
        let image = new Image();      
        image.src = createBlobURL(httpRequest.response);        
        image.onload = function (){           
           Context.drawImage(image, 0, 0);
           revokeBlobUrl( image.src );
           image = null;
        }
     }   
     httpRequest.send(null);
 }

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

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

The JSON parsing functionality is not working as expected in my app.js file

app.js: const express = require("express"); const https = require("https"); const app = express(); const port = 3000; app.get("/",function(req,res){ const url ="https://maps.googleapis.com/maps/api/geocode/jsonaddress=1600+Amphitheatre+Parkway,+Mounta ...

Iterate through an Array of Objects and exhibit a single object property in HTML one at a time by utilizing Javascript

I am working with an array of objects that contain two properties: "quote" and "author". I have a container div where I want the quotes to be displayed one by one at an interval of every 2 seconds. Currently, it is showing one letter at a time instead of d ...

Traversing an object with a loop

I'm currently working on a project that involves utilizing the swapi co API. Although I've successfully fetched results from the website, I'm struggling with displaying only specific API objects, particularly array spaceships. var linkApi=" ...

Experiencing difficulties in transmitting multipart form data from React to Express Js accurately

I am facing an issue with uploading files using Dropzone and sending them to a Java backend API from React JS. In this scenario, React sends the document to Express backend where some keys are added before forwarding the final form data to the Java endpoin ...

what strategies can be implemented to prioritize addressing validation errors in return forms

I'm currently working on a web application in asp.net mvc-5, and I have a contact form displayed in the middle of the Contact Us view. Here's the code snippet: <div class="col-sm-8 col-sm-push-4"> <h2>Contact Us1 ...

XMLHttpRequest problem: receiving status code 0 from both local and live server

I'm struggling to make this XMLHttpRequest work correctly. This is my first time using AJAX, so I'm not sure if I've formatted everything properly. I've searched all over the internet and found similar information and examples, but cert ...

What is the preset value for the payload in a vuex action?

Currently, I am utilizing an if-else statement in my Vuex action to set a default value for a payload property. Specifically, I check if the passed payload object contains a delay property; if it does not, I assign it a default value and handle appropriate ...

Press a button to activate a function on a dynamically created table using Ajax

On my website, I have an ajax function that dynamically generates a table and displays it inside a designated div. Below is the PHP code called by the Ajax function. echo "<table border='1' cellspacing='12' cellpadding='4' ...

Partially accessible Angular service within a callback function

I'm currently facing an issue in my Angular simple app related to a factory that is not fully available within a callback function. You can check out a simplified version of the application on this Plunkr link. Here's a snippet of the code: Th ...

What is the best way to trigger a modal to appear when dynamically generated items are clicked?

My objective is to retrieve specific data from the server and present it in a list format on my webpage. The list displays correctly, but I want users to be able to view additional details for each list item by clicking on it, triggering a modal popup. How ...

Is there a way to swap out values in a JavaScript Object for new ones?

I need to update the initial values of myObject with new names: let myObject = [ { name: 'X0', values: 'FALSE,TRUE' } , { name: 'X1', values: 'NORMAL,LOW,HIGH' } , { name: 'X2', values: ' ...

Unusual shadow cast by the box's silhouette

I am currently facing an issue with a box and its shadow. When I close the box, a different shadow lingers behind. I have tried troubleshooting this problem but cannot pinpoint the source. I have included the relevant code files in the specified folders. I ...

Having trouble accessing the ID of a list item using jQuery?

Can you please help me figure out why the code below is not passing the list element ID to ajax correctly: Here's the HTML: <ul id="tree"> <li><a id="1">Finance</a></li> <li><a id="2">ACC& ...

history.push() function is ineffective within a JavaScript file that does not contain a class

I've been delving into React and encountering an issue with the history.push("/dashboard") method, it's not functioning as expected. import axios from "axios"; import { GET_ERRORS, GET_PROJECT, GET_PROJECTS } from "./types"; export const createP ...

Serve static files using ExpressJS when a post request is made

My Express server is set up to serve static files for my website and it's working fine: var express = require('express'); var app = express(); var path = require('path'); var p = path.join(__dirname, '../web/public'); app ...

Using Javascript, when the command key is pressed, open the link in a new window

Currently, I am working on a Javascript function that opens links in a new tab only when the "command" key is pressed on an Apple computer. Here is what I have so far: $(document).on('click','a[data-id]',function(e){ if(e.ctrlKey|| ...

Texture mapping in THREE.JS can be applied to ExtrudeGeometry for enhancing the appearance

Currently, I am tackling an issue concerning three.js and ExtrudeGeometry. The challenge at hand involves a wave-like structure composed of multiple individual frames, each being extruded using ExtrudeGeometry. https://i.sstatic.net/juEBb.jpg My goal is ...

How to use multiple template urls in Angular 6

Currently, I am creating a front-end using Angular 6 and facing the challenge of having components with varying html structures based on the user who is logged in. The number of templates required can range from 2 to over 20, so my preference would be to ...

The setInterval function is active in various components within Angular 6

Recently, I started using Angular(6) and incorporated the setInterval function within a component. It's functioning properly; however, even after navigating to another route, the setInterval continues to run. Can someone help me determine why this is ...