Last active
October 24, 2020 21:30
-
-
Save mattlundstrom/8d961b1eaec7ef32412f3c447348be40 to your computer and use it in GitHub Desktop.
JS function that can only be fired once.
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
// ONCE | |
function once(fn, context) { | |
var result; | |
return function() { | |
if(fn) { | |
result = fn.apply(context || this, arguments); | |
fn = null; | |
} | |
return result; | |
}; | |
} | |
// Usage | |
var canOnlyFireOnce = once(function() { | |
console.log('Fired!'); | |
}); | |
canOnlyFireOnce(); // "Fired!" | |
canOnlyFireOnce(); // nada | |
// POLL | |
function poll(fn, callback, errback, 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 { | |
errback(new Error('timed out for ' + fn + ': ' + arguments)); | |
} | |
})(); | |
} | |
// Usage: ensure element is visible | |
poll( | |
function() { | |
return document.getElementById('lightbox').offsetWidth > 0; | |
}, | |
function() { | |
// Done, success callback | |
}, | |
function() { | |
// Error, failure callback | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment