Last active
October 16, 2020 15:46
-
-
Save kerimdzhanov/f6f0d2b2a57720426211 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
// The polling function | |
function poll(fn, callback, timeout, interval) { | |
var endTime = Number(new Date()) + (timeout || 2000); | |
interval = interval || 100; | |
(function p() { | |
// If the condition is met, we're done! | |
if (fn()) { | |
callback(); | |
} | |
// If the condition isn't met but the timeout hasn't elapsed, go again | |
else if (Number(new Date()) < endTime) { | |
setTimeout(p, interval); | |
} | |
// Didn't match and too much time, reject! | |
else { | |
callback(new Error('timed out for ' + fn + ': ' + arguments)); | |
} | |
})(); | |
} | |
// Usage: ensure element is visible | |
poll(function () { | |
return document.getElementById('lightbox').offsetWidth > 0; | |
}, function (err) { | |
if (err) { | |
// Error, failure callback | |
} | |
else { | |
// Done, success callback | |
} | |
}, 2000, 150); |
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
// The polling function | |
function poll(fn, timeout, interval) { | |
var dfd = new Deferred(); | |
var endTime = Number(new Date()) + (timeout || 2000); | |
interval = interval || 100; | |
(function p() { | |
// If the condition is met, we're done! | |
if (fn()) { | |
dfd.resolve(); | |
} | |
// If the condition isn't met but the timeout hasn't elapsed, go again | |
else if (Number(new Date()) < endTime) { | |
setTimeout(p, interval); | |
} | |
// Didn't match and too much time, reject! | |
else { | |
dfd.reject(new Error('timed out for ' + fn + ': ' + arguments)); | |
} | |
})(); | |
return dfd.promise; | |
} | |
// Usage: ensure element is visible | |
poll(function () { | |
return document.getElementById('lightbox').offsetWidth > 0; | |
}, 2000, 150); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment