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);