One-line pause function in plain Javascript

To keep it short, this post only deals with a simple pause function:

const pause = time => new Promise(resolve => setTimeout(resolve, time))

pause function returns a Promise when called. The Promise itself resolves after a specified amount of time, giving us the ability to chain some piece of code and delay it. Sort of a flow control mechanism for code execution.

If we imagine having a working implementation of fetchData function we can delay it for 2 seconds like so:

pause(2000).then(fetchData)

Or use it inside an async function to pause the execution between two lines for 1 second:

async function fetchAllData() {
  const data1 = await fetchData1(...)
  await pause(1000)
  const data2 = await fetchData2(...)
  return {...data1, ...data2}
}

Pretty powerful one-liner!