Best approach to implement a timer in reflex?

I wanted to implement a timer/chronometer/countdown and found two ways to do so:

  • Write the timer in python within the State, using @rx.background decorator
  • Use rx.moment with intervals + on_change to refresh the time
    I wonder what would be the most efficient option, or maybe there is another way? :thinking:

How’s this?

class TimeState(rx.State):
    show: bool = True
    countdown_second: int = 10
   #倒计时: 输入倒计时秒数,开始倒计时     show:是否将倒计时反映到state的var
    @rx.background
    async def countdown(self):
        if self.show:
            while self.countdown_second > 0:
                async with self:
                    self.countdown_second -= 1
                await asyncio.sleep(1)
        else:
            while second > 0:
                second -= 1
                await asyncio.sleep(1)
            return True

Both approach are perfectly acceptable.

Choosing which one to use will depend on the focus of the task you want to trigger periodically.

If it’s a backend task, then using background make more sense.
If you are calling something like rx.call_script() then using rx.moment will be better to reduce the exchanges between frontend and backend.

1 Like