asyncio.sleep in javascript 1

asyncio.sleep in javascript

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

/*Use like so*/

async function timeSensativeAction(){ //must be async func
  //do something here
  await sleep(5000) //wait 5 seconds
  //continue on...
}

Here is what the above code is Doing:
1. We create a function called sleep that takes in a number of milliseconds.
2. We return a new Promise that will resolve after the given number of milliseconds.
3. We create an async function called timeSensativeAction.
4. We do something.
5. We await the sleep function, which will pause the execution of the function for 5 seconds.
6. We continue on with the function.

Similar Posts