Timer events only when the form is visible

I always thought that the timer only fired when the form was displayed on the screen, but I found that it keeps firing:

  • when the browser is minimized or another tab selected
  • when another form is displayed (but it still exists in the cache in hashrouting) Edit: not True.

If you use your timer for polling the database for updates, this is probably not what you want.

Here is how you can make it perform its task only when the form is visible on the screen:

import anvil.js

class MyForm(MyFormTemplate):
  def __init__(self, **properties):
    self.init_components(**properties)
    self._interval = self.timer.interval

  def _is_app_hidden(self, **event_args):  
    # True if browser minimized or tab hidden
    return anvil.js.window.document.hidden

  def timer_tick(self, **event_args):  
    if not self._is_app_hidden():
      # do your thing
      pass

  def form_show(self, **event_args):
    # start timer
    self.timer.interval = self._interval # Edit: not necessary

  def form_hide(self, **event_args):
    # stop timer
    self.timer.interval = 0 # Edit: not necessary. The timer stops on hide.


2 Likes

If you’re able to reproduce a timer that ticks when not on the screen we can take a look
Timers should only tick when on the screen. ie if they’re not on the screen in hash routing they shouldn’t tick.

This app prints on screen every second: https://attractive-wiry-status.anvil.app

  1. if you change tab or minimize the window, you can see that it keeps ticking and does not miss a second when it is hidden (at least not on my Chrome on PC). Is this expected behavior?
  2. I was wrong (not a surprise!) about my claim that it keeps ticking when another form was displayed. It doesn’t. I got confused about a component in a hidden sidebar that kept ticking. If you close the sidebar in the demo app, you will see that it keeps ticking while hidden. Hiding the side bar does not trigger form_hide(). I guess this makes sense - you would want a component in a sidebar to be active when hidden as the sidebare could be toggled any time.
1 Like

Thanks. Yes 1 is expected behaviour. But you will probably find this might be inconsistent between different browsers.