設定XMLHttpRequest超時簡單介紹

admin發表於2017-02-10
XMLHttpRequests在執行時,當長時間沒有響應(如出現網路問題等)時,應該中止掉連線。

可以通過setTimeout()來完成這個工作:

[JavaScript] 純文字檢視 複製程式碼
var xhr = new XMLHttpRequest (); 
xhr.onreadystatechange = function () { 
 if (this.readyState == 4) { 
  clearTimeout(timeout); 
  // do something with response data 
 } 
} 
var timeout = setTimeout( function () { 
 xhr.abort(); // call error callback 
}, 60*1000 /* timeout after a minute */ ); 
xhr.open('GET', url, true); 
xhr.send();

相關文章