문제

Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.

https://leetcode.com/problems/array-prototype-last/

 

예시

0.1초 후 then 안에 있는 함수가 실행된다.

 

코드

/**
 * @param {number} millis
 * @return {Promise}
 */
async function sleep(millis) {
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            resolve();
        }, millis);
    });
}

/** 
 * let t = Date.now()
 * sleep(100).then(() => console.log(Date.now() - t)) // 100
 */

sleep 함수가 Promise 객체를 반환하도록 하였다. sleep 함수의 인자로 들어온 millis 만큼 지연시킨 후, then에 있는 함수를 실행해야 하기 때문에 setTimeout을 이용하였다. millis 만큼의 시간이 흐르면 일이 성공적으로 끝났음을 알리는 resolve() 함수를 호출한다. 요구사항에서 value를 넘기는 것은 필요하지 않아서 resolve 함수의 인자로 아무 것도 넣어주지 않았다.

728x90

+ Recent posts