Sleep() 함수란?
Sleep() 함수를 사용하면 함수의 실행을 정해진 시간 동안 일시적으로 멈출 수 있습니다. C나 PHP 같은 프로그래밍 언어에서는 sleep(sec) 형태로 호출하고, Java는 Thread.sleep(), Python은 time.sleep(), Go는 time.Sleep(2 * time.Second)를 사용해 동일한 기능을 구현합니다.
그러나 자바스크립트(JavaScript)에는 이런 종류의 sleep 함수가 기본적으로 제공되지 않습니다. 다행히 ES2018에 도입된 Promise와 async/await 덕분에 sleep() 기능을 아주 손쉽게 구현할 수 있게 되었습니다. 지금부터 핵심 내용을 간단히 살펴보겠습니다.
문법 1 - then()과 함께 사용하기
sleep(밀리초 단위 시간).then(() => {
// 코드
})
위와 같이 sleep 함수를 then 콜백과 함께 사용할 수 있습니다.
문법 2 - async/await와 함께 사용하기
const work = async () => {
await sleep(밀리초 단위 시간)
// 코드
}
work()
위와 같이 sleep 함수를 async/await 함수와 함께 사용하는 방법도 있습니다.
예제
다음 예제에서는 async/await 함수와 함께 sleep()을 사용했습니다. sleep 함수 앞에 await 키워드를 붙여 작업이 순서대로 진행되도록 처리했습니다. 먼저 async 함수가 시작되면 "Hello Tutorix"라는 텍스트가 화면에 출력됩니다. 그다음 sleep 함수를 통해 3초간 실행이 일시 중지되고, 지정된 시간이 지나면 sleep 함수 뒤에 있는 텍스트("Welcome to ........")가 출력됩니다. 이 과정은 루프가 종료될 때까지 반복되며, 결과적으로 텍스트는 아래 실행 결과와 같이 총 19번 출력됩니다.
<html>
<body>
<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function Tutor() {
document.write('Hello Tutorix');
for (let i = 1; i < 20; i++) {
await sleep(3000);
document.write(i + " " + "Welcome to tutorix" + " " + "</br>");
}
}
Tutor()
</script>
</body>
</html>
실행 결과
Hello Tutorix // 3초 후 1 Welcome to tutorix // 3초 후... 루프가 끝날 때까지 3초마다 텍스트가 반복 출력됩니다 2 Welcome to tutorix 3 Welcome to tutorix 4 Welcome to tutorix 5 Welcome to tutorix 6 Welcome to tutorix 7 Welcome to tutorix 8 Welcome to tutorix 9 Welcome to tutorix 10 Welcome to tutorix 11 Welcome to tutorix 12 Welcome to tutorix 13 Welcome to tutorix 14 Welcome to tutorix 15 Welcome to tutorix 16 Welcome to tutorix 17 Welcome to tutorix 18 Welcome to tutorix 19 Welcome to tutorix