Search code examples
javascripttimeoutdelay

how to add delay before returning a value in javascript function


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;
}

Solution

  • 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