Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active July 20, 2023 15:58
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 nathansmith/ae95088276c5d3610d3e5a8fdcac2504 to your computer and use it in GitHub Desktop.
Save nathansmith/ae95088276c5d3610d3e5a8fdcac2504 to your computer and use it in GitHub Desktop.
Sleep function in JavaScript
// ===============
// Sleep function.
// ===============
const sleep = async (seconds = 0) => {
// Expose promise.
return new Promise((resolve) => {
// Set timer.
setTimeout(() => {
// Resolve promise.
resolve(undefined);
// Delay.
}, seconds * 1000);
});
};
// =====================================
// Test function: `await` function call.
// =====================================
const testFunction1 = async () => {
// Set delay.
const delay = 5;
// Wait for delay.
await sleep(delay);
// Continue.
console.log(`Seconds slept: ${delay}`);
};
// ========================================
// Test function: `await` variable instead.
// ========================================
const testFunction2 = async () => {
// Set delay.
const delay = 10;
// Assign value.
const zzz = sleep(delay);
// Wait for delay.
await zzz;
// Continue.
console.log(`Seconds slept: ${delay}`);
};
// ====================================
// Test function: uses `then` chaining.
// ====================================
// Test function.
const testFunction3 = () => {
// Set delay.
const delay = 15;
// Wait for delay.
sleep(delay).then(() => {
// Continue.
console.log(`Seconds slept: ${delay}`);
});
};
// ====================
// Call test functions.
// ====================
// Logs after 15 seconds.
testFunction3();
// Logs after 10 seconds.
testFunction2();
// Logs after 5 seconds.
testFunction1();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment