cancel a fetch request in JavaScript

JavaScript

🤖 Code Explanation

xhr.onprogress = function(event) {

if (event.lengthComputable) {

alert(`Received ${event.loaded} of ${event.total} bytes`);

} else {

alert(`Received ${event.loaded} bytes`); // no Content-Length

}
};

xhr.onerror = function() {

alert("Request failed");

};

This code creates a new XMLHttpRequest object, configures it to make a GET request to the specified URL, and then sends that request. The onload event handler is called when the response is received, and the onprogress event handler is called periodically to update the caller on the request's progress. Finally, the onerror event handler is called if the request fails.

Download SpellBox today