Below is an illustration taken from MDN. The example showcases two buttons - one for sending a request and the other for canceling it.
var controller = new AbortController();
var signal = controller.signal;
var downloadBtn = document.querySelector('.download');
var abortBtn = document.querySelector('.abort');
downloadBtn.addEventListener('click', fetchVideo);
abortBtn.addEventListener('click', function() {
controller.abort();
console.log('Download aborted');
});
function fetchVideo() {
...
fetch(url, {signal}).then(function(response) {
...
}).catch(function(e) {
reports.textContent = 'Download error: ' + e.message;
})
}
In my scenario, there's a unique factor of having a query
parameter. If a fetch operation is ongoing but not yet completed, and there's a change in the query
parameter - how can I automatically send a new request while canceling the previous one?