Created
November 5, 2018 12:12
-
-
Save laphilosophia/f6c05a8e6de4937a6d62e9da86626b6f to your computer and use it in GitHub Desktop.
Javascript polling functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// deferred | |
function poll(fn, timeout, interval) { | |
let endTime = Number(new Date()) + (timeout || 2000) | |
interval = interval || 100 | |
let checkCondition = (resolve, reject) => { | |
// If the condition is met, we're done! | |
let result = fn() | |
if (result) { | |
resolve(result) | |
} else if (Number(new Date()) < endTime) { | |
// If the condition isn't met but the timeout hasn't elapsed, go again | |
setTimeout(checkCondition, interval, resolve, reject) | |
} else { | |
// Didn't match and too much time, reject! | |
reject(new Error('timed out for ' + fn + ': ' + arguments)) | |
} | |
} | |
return new Promise(checkCondition) | |
} | |
poll(() => { | |
return document.getElementById('lightbox').offsetWidth > 0 | |
}, 2000, 150).then(() => { | |
}).catch(() => { | |
}) | |
/* *** */ | |
// without deferred | |
function poll(fn, callback, errback, timeout, interval) { | |
let endTime = Number(new Date()) + (timeout || 2000) | |
interval = interval || 100 | |
(function p() { | |
// If the condition is met, we're done! | |
if (fn()) { | |
callback() | |
} else if (Number(new Date()) < endTime) { | |
// If the condition isn't met but the timeout hasn't elapsed, go again | |
setTimeout(p, interval) | |
} else { | |
// Didn't match and too much time, reject! | |
errback(new Error('timed out for ' + fn + ': ' + arguments)) | |
} | |
})() | |
} | |
poll(() => { | |
return document.getElementById('lightbox').offsetWidth > 0 | |
}, () => { | |
// Done, success callback | |
}, () => { | |
// Error, failure callback | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment