0

I need to add a 2 seconds delay before returning a value in Javascript function

function slowFunction(num) {
  console.log("Calling slow function");
 
  // 2 seconds delay here

  return num * 2;
}

1 Answers1

2

A couple of ways to do this.

I prefer using promises.

function sleep(delay: number): Promise<void>{
   return new Promise( (res) => {
        setTimeout(()=>res(),delay)
   })
}

async function slowFunction(num) {
  console.log("Calling slow function");
  await sleep(2000)
  // 2 seconds delay here

  return num * 2;
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

albseb
  • 169
  • 5