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)) 
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