Skip to content

Instantly share code, notes, and snippets.

@JamesTheHacker
Last active September 27, 2017 20:59
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 JamesTheHacker/2e784019a165327544bb5ea2602c47f8 to your computer and use it in GitHub Desktop.
Save JamesTheHacker/2e784019a165327544bb5ea2602c47f8 to your computer and use it in GitHub Desktop.
Supporting file for the following article:
// This function waits for an unknown amount of time
const wait = (delay, callback) => {
// setInterval returns an ID. We need this to stop the timer
const id = setInterval(() => {
// Generate a random number between 0 and 1
const rand = Math.random();
if (rand > 0.95) {
// Call the callback function. Note the first parameter is an error
callback(null, 'Congratulations, you have finished waiting.');
// Stop the timer
clearInterval(id);
} else if (rand < 0.01) {
// Call the callback function. Note we're setting an error now
callback('Could not wait any longer!', null);
// Stop the timer
clearInterval(id);
} else {
// Print to STDOUT
console.log('Waiting ...');
}
}, Number(delay));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment