DEV Community

Luka Vidaković
Luka Vidaković

Posted on

One-line pause function in plain Javascript

This is first post in series, explaining how to build a plain javascript code scheduler. Schedulers are mandatory tool to periodically fetch the data from an API. Something needs to control at what point in time the requests are to be made. Purpose of the series is to prove that it can be done in a couple of lines of plain Javascript.

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

const pause = time => new Promise(resolve => setTimeout(resolve, time))
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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}
}
Enter fullscreen mode Exit fullscreen mode

Pretty powerful one-liner, and that's not even covering all the possibilities. In the following posts we'll build on this idea of a pause and make it a crucial part of our scheduler.

Top comments (1)

Collapse
 
lalithk31232596 profile image
Lalith Kumar

Exceptional article, learnt a lot.