[Easy] LeetCode JS 30 - 2621. Sleep
March 5, 2024
Summary
Learn how to implement an asynchronous 'sleep' function in JavaScript using promises and setTimeout. Improve your code's readability and manage asynchronous tasks smoothly. Explore the solution for pausing code execution in JS with ease.
LeetCode 30 Days of JavaScript
This question is from LeetCode's 30 Days of JavaScript Challenge
2621. SleepQuestion Prompt
JavaScript has a built-in setTimeout to pause and resume code, but it's a bit awkward to use. Can we make it work more smoothly, like the 'sleep' function in other languages such as Java and Python but in an asynchronous way?
// we can do
console.log("Explain");
await sleep(3000); // Pause for 3 second
console.log("This");
// or do
console.log("Explain");
sleep(3000).then(() => {
console.log("This"); // Only logs after 3 seconds
});
Solutions
Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!
We can implement sleep in the following steps:
- Declares a function named
sleepthat expects aduration(in milliseconds) as input. Theasynckeyword makes this function asynchronous, meaning it can handle tasks that take time without blocking the main thread. - Creates a new Promise object, which is a way to manage asynchronous operations. The Promise constructor takes a callback function (called the executor) that handles how the Promise will be resolved or rejected.
- Schedules a timeout using JavaScript's built-in
setTimeoutfunction. After the specifieddurationin milliseconds, theresolvefunction will be called.resolveis a function provided by the Promise object, used to indicate that the asynchronous operation has completed successfully. - Lastly, returns the created Promise object, allowing other parts of the code to interact with it and wait for the sleep to finish.
async function sleep(duration) {
return new Promise((resolve) => setTimeout(resolve, duration));
}