how to sleep in javascript

In JavaScript, there is no built-in sleep() function like in other programming languages that allows you to pause the execution of your code for a specified amount of time. However, you can use a combination of setTimeout() and Promises to achieve a similar effect.

Here is an example of how you can use setTimeout() and Promises to create a sleep() function in JavaScript:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

This function takes a single argument ms, which represents the number of milliseconds to wait before resolving the Promise. When called, the function returns a Promise that resolves after the specified number of milliseconds.

You can use the sleep() function like this:

console.log("Start");
await sleep(1000); // wait for 1 second
console.log("End");

This code will output "Start" immediately, wait for 1 second using the sleep() function, and then output "End".

댓글

이 블로그의 인기 게시물

PYTHONPATH, Python 모듈 환경설정

You can use Sublime Text from the command line by utilizing the subl command

git 명령어

[gRPC] server of Java and client of Typescript

[Ubuntu] Apache2.4.x 설치

Create topic on Kafka with partition count, 카프카 토픽 생성하기

리눅스의 부팅과정 (프로세스, 서비스 관리)

Auto-populate a calendar in an MUI (Material-UI) TextField component

The pierce selector in Puppeteer