DEV Community

Luka Vidaković
Luka Vidaković

Posted on • Updated on

Improving our periodic code scheduler

Previously, we constructed a pretty simple and naive system that periodically runs a function. Not great, not terrible. Let's try to make it better one step at a time. Main drawback was that there was no way to stop it, but we'll get there. First, we are going to move some logic to an async generator. They work great with infinite streams. Our driving logic is basically an infinite stream of events that happen at a specified amount of time. We'll move the part that generates pause events to an async generator, while the loop will slightly change it's face and become a bit slicker to use, even though it might also need a refactor in the future.

From previous code:

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

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

Enter fullscreen mode Exit fullscreen mode

And it's usage:

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

runPeriodically(logTime, 2000)
Enter fullscreen mode Exit fullscreen mode

We move pause generation to an async generator and tweak the iterating loop:

async function* cycle(time) {
    while(true) {
        yield pause(time)
    }
}

async function runPeriodically(callback, time) {
    for await (let tick of cycle(time)) {
        await callback()
    }
}
Enter fullscreen mode Exit fullscreen mode

runPeriodically function can still be used exactly the same and is still with the fundamental problem of not being able stop the loop once it's been started. But the loop now only worries about the actual code that runs on every iteration, while async generator implements rudimental logic to yield pause events. Generators offer some unique set of features that allow them to communicate back and forth with the rest of the code and that's something we'll use to construct a more robust mechanism. Upcoming posts will provide several tweaks and fixes that give greater control over this kind of code runner.

Top comments (0)