相关文章推荐
寂寞的牛肉面  ·  使用ByteBuffer ...·  1 年前    · 
爱运动的青椒  ·  VBA ...·  1 年前    · 

1. 设置请求超时时间: xhr.timeout, 如果超时, 请求会自动终止; 参数是毫秒;

2. 设置请求超时监听函数: xhr.ontimeout, 如果请求超时, 则会触发ontimeout事件的监听函数;

var xhr = new XMLHttpRequest();
var url = '/server';
xhr.ontimeout = function () {
  console.error('The request for ' + url + ' timed out.');
xhr.onload = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      // 处理服务器返回的数据
    } else {
      console.error(xhr.statusText);
xhr.open('GET', url, true);
// 指定 10 秒钟超时
xhr.timeout = 10 * 1000;
xhr.send(null);