To ensure your request call and timeout function are synchronized, you can combine them using the following method in pure JavaScript:
- Encapsulate your xhr request in a Promise
var makeRequest = function (url, method) {
// Create the XHR request
var request = new XMLHttpRequest();
// Return it as a Promise
return new Promise(function (resolve, reject) {
// Listener to handle completed requests
request.onreadystatechange = function () {
// Only run if the request is complete
if (request.readyState !== 4) return;
// Process the response
if (request.status >= 200 && request.status < 300) {
// Resolve if successful
resolve(request);
} else {
// Reject if failed
reject({
status: request.status,
statusText: request.statusText
});
}
};
// Setup HTTP request
request.open(method || 'GET', url, true);
// Send the request
request.send();
});
};
- Create a waiting function
var justWait = function(interval) {
return new Promise(resolve => {
setTimeout(resolve, interval);
})
}
- Combine both functions
// Apply animation here
Promise.all([
makeRequest('https://some/url/here', 'GET'),
justWait(1000)
]).then(res => {
// Remove animation here
})
.catch(err => {
// Remove animation in case of error
});
This ensures that your animation will last at least as long as the justWait
interval, but will wait for the xhr request to finish if it takes longer.
If you are using the rxjs
library, you can use zip
instead of Promise.all
, while maintaining the same concept.