Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Created November 5, 2018 12:12
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 laphilosophia/f6c05a8e6de4937a6d62e9da86626b6f to your computer and use it in GitHub Desktop.
Save laphilosophia/f6c05a8e6de4937a6d62e9da86626b6f to your computer and use it in GitHub Desktop.
Javascript polling functions
// 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