Recent Posts
Recent Comments
게으른개발너D
[Promise] Sleep ⭐️ 본문
https://leetcode.com/problems/sleep/
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
solution
/**
* @param {number} millis
*/
async function sleep(millis) {
return await new Promise(resolve => {
setTimeout(resolve, millis);
})
}
/**
* let t = Date.now()
* sleep(100).then(() => console.log(Date.now() - t)) // 100
*/
Promise에서는 첫번째 파라미터 값인 resolve와 두번째 파라미터 값인 reject가 있는데, Promise 안에서 resolve와, reject를 사용하면 return 값처럼 해당 값들이 반환된다.
typescript
async function sleep(millis: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, millis);
});
}
/**
* let t = Date.now()
* sleep(100).then(() => console.log(Date.now() - t)) // 100
*/
'알고리즘 > 과제' 카테고리의 다른 글
[Array] Filter Elements from Array (filter 구현하기) (0) | 2023.07.03 |
---|---|
[Function, Closure] Function Composition (feat. reduceRight) (0) | 2023.07.03 |
[Array] Array Reduce Transformation (reduce 정의하기) (0) | 2023.07.03 |
[Function, Closure] Counter ⭐️ (0) | 2023.07.03 |
[Array] Array Prototype Last (0) | 2023.07.03 |
Comments