DEV Community

Luka Vidaković
Luka Vidaković

Posted on

3 1

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

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

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

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

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay