[Easy] LeetCode JS 30 - 2621. Sleep
March 5, 2024
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee
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
sleep
that expects aduration
(in milliseconds) as input. Theasync
keyword 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
setTimeout
function. After the specifiedduration
in milliseconds, theresolve
function will be called.resolve
is 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));
}