Sleep 非同步

Given a positive integer millis, write an asyncronous 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

 

解法:

這是在講非同步的概念,指定要多長時間才能夠做回應

const sleep = async(millis: number) => {
    return await new Promise<void>(resolve=>  setTimeout(()=> resolve(), millis))
}

Copyright © 2025 - All right reserved