AbortController接口表示一个控制器对象,允许你根据需要中止一个或多个 Web请求。

    https://developer.mozilla.org/zh-CN/docs/Web/API/AbortController

    1. const controller = new AbortController();
    2. let signal = controller.signal;
    3. const downloadBtn = document.querySelector('.download');
    4. const abortBtn = document.querySelector('.abort');
    5. downloadBtn.addEventListener('click', fetchVideo);
    6. abortBtn.addEventListener('click', function() {
    7. controller.abort();
    8. console.log('Download aborted');
    9. });
    10. function fetchVideo() {
    11. //...
    12. fetch(url, {signal}).then(function(response) {
    13. //...
    14. }).catch(function(e) {
    15. reports.textContent = 'Download error: ' + e.message;
    16. })
    17. }