2

I need to make a delay or sleep to full pause the code

I this:

setTimeout(() => {
    console.log("Hello")
}, 2000)

console.log("World")

But the log "World" prints first

Previously I'm using python and I used a code:

print("Hello")

time.sleep(2000)

print("World")

It's a success the word "Hello" prints first before world because of the time.sleep()

but I'm searching javascript code

If there's a code for it please share

  • 1
    _"I tried"_ Please show, not tell. Edit the question and include a [mcve] of you efforts. – evolutionxbox May 07 '21 at 10:12
  • Hello, the use of setTimeout was the right answer. Just put the code you want to execute first before this function, and the code you want to execute after 2 secondes inside it. console.log("Hello") setTimeout(() => { console.log("World") }, 2000) – Bloodbee May 07 '21 at 10:23
  • As [M.Hassan Nasir](https://stackoverflow.com/questions/67432953/how-to-make-a-sleep-or-full-pause-in-javascript#comment119190848_67432953) said, [the answer is here](https://stackoverflow.com/a/39914235/12425097). – LaytonGB May 07 '21 at 10:40

1 Answers1

2

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

async function wait() {
  console.log('sleeping...');
  await sleep(2000); // 2000 ms = 2 sec
  console.log('done');
}

wait();
era-net
  • 387
  • 1
  • 11