How to Wait 1 Second in Javascript

0 min read 120 words

If you need your Javascript code to wait one (1) second (or more) while executing, then there are a couple of ways to achieve this.

Option 1 – Creating a delay Promise

function delay(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}

delay(1000).then(() => console.log('ran after 1 second elapsed'));

Option 2 – Using setTimeout

setTimeout(function(){ 
  console.log("Ready")
}, 1000);

Option 3 – Using an async Promise

async function test() {
  console.log('start timer');
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log('after 1 second');
}

test();

Option 4 – Creating a custom sleep function

function sleep(num) {
  let now = new Date();
  const stop = now.getTime() + num;
  while(true) {
    now = new Date();
    if(now.getTime() > stop) return;
  }
}

sleep(1000)
console.log('delay 1 second');
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts