Since fetch() doesn’t provide any way for setting a timeout for requests by design, I’ve implemented a simple wrapper Promise based solution which might come handy for your remote API calls.
var FETCH_TIMEOUT = 5000;
new Promise(function(resolve, reject) {
var timeout = setTimeout(function() {
reject(new Error('Request timed out'));
}, FETCH_TIMEOUT);
fetch('https://example.com/request')
.then(function(response) {
clearTimeout(timeout);
if (response && response.status == 200) return response.json();
else reject(new Error('Response error'));
})
.then(function(responseObject) {
// process results
resolve();
})
.catch(function(err) {
reject(err);
});
})
.then(function() {
// request succeed
})
.catch(function(err) {
// error: response error, request timeout or runtime error
});