[Leetcode] JS 30 Sleep
Question
Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.
Example 1:
Input: millis = 100
Output: 100
Explanation: It should return a promise that resolves after 100ms.
let t = Date.now();
sleep(100).then(() => {
console.log(Date.now() - t); // 100
});
Example 2:
Input: millis = 200
Output: 200
Explanation: It should return a promise that resolves after 200ms.
Constraints:
1 <= millis <= 1000
My Solution
/**
* @param {number} millis
* @return {Promise}
*/
async function sleep(millis) {
return new Promise(resolve => {setTimeout(resolve,millis)});
}
/**
* let t = Date.now()
* sleep(100).then(() => console.log(Date.now() - t)) // 100
*/
Key Takeaways
The key rule in this question is that async functions always return a Promise. Since we see Promise.then() being used in the test cases, sleep() must return a Promise. We do not need to use await inside the sleep() function because we are not executing the Promise immediately, but rather returning a Promise that will be handled by .then().
Moreover, based on our last article about Promise here https://404-peace-not-found.ghost.io/ghost/#/site, you can also restructure your code with async/await instead of .then() .
First method
function sleep(millis) {
return new Promise(resolve => setTimeout(resolve, millis));
}
async function test() {
let t = Date.now();
await sleep(100); // will wait Promise to be solved
console.log(Date.now() - t); // about 100
}
test();
Second Method
async function sleep(millis) {
let t = Date.now();
await new Promise(resolve => {
setTimeout(() => {
console.log(Date.now() - t);
resolve(); // we have to add resolve() here otherwise this await will get stuck
}, millis);
});
}
Comments ()