Last active
July 20, 2023 15:58
-
-
Save nathansmith/ae95088276c5d3610d3e5a8fdcac2504 to your computer and use it in GitHub Desktop.
Sleep function in JavaScript
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
// =============== | |
// 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