AbortController を試す

1. このページの目的

AbortController - Web API | MDN の例を試す。

2. デモ

fetch で JSON を取得します。

3. コード

HTML

<button id="run-fetch">run fetch</button>
<button id="abort-fetch">abort fetch</button>
<p id="report"></p>

JavaScript

let controller, signal;

const runBtn = document.querySelector('#run-fetch');
const abortBtn = document.querySelector('#abort-fetch');
const reportElm = document.querySelector('#report');
const url = "./fetch-target.json.php";

runBtn.addEventListener('click', () => {
  report.textContent = '';

  controller = new AbortController();
  signal = controller.signal;

  fetch(url, {signal})
  .then(response => response.json())
  .then(data => {
    report.textContent = 'JSON: ' + JSON.stringify(data);
  })
  .catch(e => {
    report.textContent = 'Download error: ' + e.message;
  })
  ;
});

abortBtn.addEventListener('click', function() {
  if (controller) {
    controller.abort();
  }
});

fetch-target.json.php

<?php
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Type: application/json; charset=utf-8');
sleep(3);
?>
{
  "name": "Taro",
  "hobby": "piano"
}

4. メモ

5. 参考