在JavaScript中进行远程请求(例如使用XMLHttpRequest
或者fetch
API)时,有时会遇到请求因为网络延迟或者服务器响应慢而长时间挂起的情况。为了避免这种情况,可以设置请求的超时时间。
超时时间:是指一个操作可以执行的最长时间。如果在这个时间内操作没有完成,那么就认为操作失败,并且可以执行一些后续的处理逻辑。
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.timeout = 5000; // 设置超时时间为5秒
xhr.ontimeout = function () {
console.log('请求超时');
};
xhr.onerror = function () {
console.log('请求发生错误');
};
xhr.onload = function () {
if (xhr.status === 200) {
console.log('请求成功:', xhr.responseText);
} else {
console.log('请求失败:', xhr.statusText);
}
};
xhr.send();
fetch
API 和 AbortController
fetch
API本身不支持超时设置,但是可以通过结合AbortController
来实现超时控制。
const controller = new AbortController();
const signal = controller.signal;
// 设置超时时间为5秒
const timeoutId = setTimeout(() => controller.abort(), 5000);
fetch('https://api.example.com/data', { signal })
.then(response => {
clearTimeout(timeoutId); // 清除超时计时器
if (!response.ok) {
throw new Error('网络响应不是OK');
}
return response.json();
})
.then(data => console.log('请求成功:', data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('请求超时');
} else {
console.log('请求失败:', error);
}
});
通过合理设置超时时间,可以提高应用的健壮性和用户体验。
领取专属 10元无门槛券
手把手带您无忧上云