Saturday, May 20, 2023
HomeSoftware EngineeringHow you can Wait 1 Second in Javascript

How you can Wait 1 Second in Javascript


Should you want your Javascript code to attend one (1) second (or extra) whereas executing, then there are a few methods to attain this.

Choice 1 – Making a delay Promise

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

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

Choice 2 – Utilizing setTimeout

setTimeout(operate(){ 
  console.log("Prepared")
}, 1000);

Choice 3 – Utilizing an async Promise

async operate check() {
  console.log('begin timer');
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log('after 1 second');
}

check();

Choice 4 – Making a customized sleep operate

operate sleep(num) {
  let now = new Date();
  const cease = now.getTime() + num;
  whereas(true) {
    now = new Date();
    if(now.getTime() > cease) return;
  }
}

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments