Using timers

When creating a workflow, you can use the 'timer' construct to delay actions on the device. The following example walks through a basic timer.

const createTimer = (relay) => {
  relay.on(`start`, async () => {
    await relay.setVar(`tick_num`, 1)
    await relay.startTimer(await relay.getVar(interval, 60))
    relay.say(`starting timer`)
  })

  relay.on(`button`, async (button, taps) => {
    if (button === `action` && taps === `single`) {
      await relay.say(`stopping timer`)
      await relay.terminate()
    } else {
      relay.say(`dude ! stop pressing buttons`)
    }
  })

  relay.on(Event.TIMER, async () => {
    const num = relay.getVar(`tick_num`)
    const count = relay.getVar(`count`, 5)

    if (num < count) {
      await relay.say(`stopping timer`)
      await relay.terminate()
    } else {
      await relay.say(`${num}`)
      await relay.setVar(`tick_num`, ++num)
    }
  })
}

export default createTimer

Here, we're using startTimer() when the workflow starts, with a default value of 60 seconds (the getVar() function will return a configured argument if there is one).

When 60 seconds have elapsed, the relay.on(Event.TIMER) event will fire. Here we are waiting for 5 ticks of the timer to elapse, again configurable with an argument on the workflow. Once you have this code running, you can point your Relay device to the workflow by registering the workflow with the Relay CLI:

relay workflow:create:phrase -n timer -u server.ngrok.io/timer --trigger="timer" -a interval=12 --install=990007560055555

We have over-ridden the default by specifying a 12 second interval, and we should see a one minute timer on the Relay device when we speak the phrase 'Timer' into the assistant. We're using ngrok here to host our workflow locally for debug purposes.