Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Adds a timeout to a JavaScript promise, rejects if not resolved within timeout period
* Wraps a promise in a timeout, allowing the promise to reject
* if not resolved within a specified period of time.
* @param {integer} ms - milliseconds to wait before rejecting
* promise if not resolved
* @param {Promise} promise to monitor
* @Example
* promiseTimeout(1000, fetch(''))
* .then(function(cvData){
* alert(cvData);
* })
* .catch(function(){
* alert('request either failed or timedout');
* });
function promiseTimeout(ms, promise){
return new Promise(function(resolve, reject){
// create a timeout to reject promise if not resolved
var timer = setTimeout(function(){
reject(new Error("promise timeout"));
}, ms);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.