Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

sleep()의 자바 스크립트 버전은 무엇입니까?

<시간/>

JavaScript에는 기본 절전 기능이 없습니다. 그러나 이 제한을 해결하는 데 사용할 수 있는 몇 가지 해결 방법이 있습니다. 절전 기능을 구현하는 가장 쉬운 방법 중 하나는 setTimeout 및 async/await를 사용하여 자체 절전 기능을 만드는 것입니다.

예시

const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds))
// Using callbacks
sleep(1000).then(() => console.log("waited 1 second!"))
// Using async await
const waitASec = async () => {
   await sleep(1000)
   console.log("waited 1 second!")
}
waitASec()

출력

waited 1 second!
waited 1 second!