Given a positive integer millis, write an asyncronous function that sleeps for millis milliseconds. It can resolve any value.
給予一個正整數 millis,寫一個可以休眠 millies 毫秒的非同步函式。它可以解析任何的值。
Example 1:
Input: millis = 100 Output: 100
Example 2:
Input: millis = 200 Output: 200
solution:
題目需要我們寫一個非同步的函式,且提供需延遲設定的秒數當作 input 傳入這個函式中,
我們先運用 return new Promise() 來回傳新的非同步函示,
接著我們將 resolve, millis 依序放入 setTimeout 中,
當 millis 秒數結束時呼叫 resolve 來結束 Promise,
以此達到延遲的功能。
Code 1: BigO(1)
async function sleep(millis) { return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve() },millis) }) };
FlowChart:
Example 1
let t = Date.now() sleep(100).then(() => console.log(Date.now() - t)) // 100
Example 2
let t = Date.now() sleep(200).then(() => console.log(Date.now() - t)) // 200