Skip to content

Instantly share code, notes, and snippets.

@imbcmdth
Last active June 20, 2017 15:46
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 imbcmdth/bbc6e93c18ec2236af442b9929189ed4 to your computer and use it in GitHub Desktop.
Save imbcmdth/bbc6e93c18ec2236af442b9929189ed4 to your computer and use it in GitHub Desktop.
// Return a function that allows the passed-in function to be called
// at most `times` times
let numTimes = (cb, times) => (...args) => {
if (times) {
time--;
return cb(...args);
}
}
// Allow a function to be called only once
let oneTime = (cb) => numTimes(cb, 1);
// Set a timer to call a callback later
// Everything after the callback argument is passed to the callback
// if it times-out
let timer = (ms, cb, ...args) => {
setTimeout(cb, ms, ...args);
return cb;
}
// Set a timer to call a function and return the function. The resulting
// function can only be called once so which ever invokes it first (the
// timer or the receiver of the callback) wins
let timeoutable = (ms, err, cb) => timer(ms, oneTime(cb), err);
// Examples:
// Case 1: Invoke immediately
// Notes: The return value from the function is properly passed up the chain and prints on the REPL
timeoutable(2000, 'boo', (m) => m)('yay'); // immediately -> "yay"
// Case 2: Callback in time
setTimeout(timeoutable(2000, 'boo', console.log.bind(console)), 1000, 'yay'); // after 1 second -> 'yay'
// Case 2: Callback too late time
setTimeout(timeoutable(2000, 'boo', console.log.bind(console)), 3000, 'yay'); // after 2 seconds -> 'boo'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment