DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Luka Vidaković
Luka Vidaković

Posted on

Run code periodically using Promises

Previous post describes an implementation of a one-liner pause mechanism using a Promise. Here it is again:

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

This will be our mechanism to pause execution between successive calls. Simplest implementation(with some flaws) of a periodic code execution would look something like this:

async function runPeriodically(callback, time) {
  while (true) {
    await callback()
    await pause(time)
  }
}

runPeriodically function receives 2 parameters, a callback function which executes some code and time which is an integer specifying the delay between 2 consecutive calls of a callback. The loop itself is an infinite loop, because of the true condition which will never change. Usage example:

function logTime() {
    const time = new Date()
    console.log(time.toLocaleTimeString())
}

runPeriodically(logTime, 2000)

This would run indefinitely and log out current time every 2 seconds. Having an infinite loop without any means of stopping it is a serious limitation and we'll make it right in the following posts. Maybe in the end there won't be any loops at all, at least not explicitly defined ones πŸ™ƒ

Top comments (1)

Collapse
 
lalithk31232596 profile image
Lalith Kumar

thank you, it was helpful

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.