게으른개발너D

[Promise] Sleep ⭐️ 본문

알고리즘/과제

[Promise] Sleep ⭐️

lazyhysong 2023. 7. 3. 18:15

https://leetcode.com/problems/sleep/

 

Sleep - LeetCode

Can you solve this real interview question? 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 retur

leetcode.com

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
 */
Comments