Wilfredo Mitra
Wilfredo Mitra

Reputation: 23

How to make a sleep or full pause in javascript

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 🙏

Upvotes: 2

Views: 278

Answers (1)

era-net
era-net

Reputation: 387

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();

Upvotes: 2

Related Questions