javascriptajaxxmlhttprequestabortthread-abort

Abort all instances of XMLHttpRequest


I have this line of code that calls the function SigWebRefresh at specified intervals (50 milliseconds).

tmr = setInterval(SigWebRefresh, 50);

SigWebRefresh performs 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);
}

I had use clearInterval that clears a timer set with the setInterval() method.

 clearInterval(tmr);    

I want to abort all XMLHttpRequest but xhr2.abort(); only aborts one instance of the request. How to abort all uncompleted XmlHttpRequest ?


Solution

  • Try pushing each xhr2 variable to an array , utilize Array.prototype.forEach to abort each xhr2 variable stored

    var requests = [];
    
    function SigWebRefresh(){   
        xhr2 = new XMLHttpRequest();
        requests.push(xhr2);    
        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);
    }
    
    // abort all requests
    requests.forEach(function(request) {
      request.abort()
    })