Skip to content

Instantly share code, notes, and snippets.

@zachad
Forked from twmbx/vanilla-ajax-poll.js
Created April 16, 2018 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachad/f7f7775938963f0b61927330f768fbf5 to your computer and use it in GitHub Desktop.
Save zachad/f7f7775938963f0b61927330f768fbf5 to your computer and use it in GitHub Desktop.
Polling in JS with an async ajax call that returns a promise ( modified from: https://davidwalsh.name/javascript-polling )
// The polling function
function poll(fn, timeout, interval) {
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
var checkCondition = function(resolve, reject) {
var ajax = fn();
// dive into the ajax promise
ajax.then( function(response){
// If the condition is met, we're done!
if(response.data.var == true) {
resolve(response.data.var);
}
// If the condition isn't met but the timeout hasn't elapsed, go again
else if (Number(new Date()) < endTime) {
setTimeout(checkCondition, interval, resolve, reject);
}
// Didn't match and too much time, reject!
else {
reject(new Error('timed out for ' + fn + ': ' + arguments));
}
});
};
return new Promise(checkCondition);
}
// Usage: get something via ajax
poll(function() {
return axios.get('something.json');
}, 2000, 150).then(function() {
// Polling done, now do something else!
}).catch(function() {
// Polling timed out, handle the error!
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment