timer_documentation.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from nicegui import ui
  2. from . import doc
  3. @doc.demo(ui.timer)
  4. def main_demo() -> None:
  5. from datetime import datetime
  6. label = ui.label()
  7. ui.timer(1.0, lambda: label.set_text(f'{datetime.now():%X}'))
  8. @doc.demo('Activate, deactivate and cancel a timer', '''
  9. You can activate and deactivate a timer using the `active` property.
  10. You can cancel a timer using the `cancel` method.
  11. After canceling a timer, it cannot be activated anymore.
  12. ''')
  13. def activate_deactivate_demo():
  14. slider = ui.slider(min=0, max=1, value=0.5)
  15. timer = ui.timer(0.1, lambda: slider.set_value((slider.value + 0.01) % 1.0))
  16. ui.switch('active').bind_value_to(timer, 'active')
  17. ui.button('Cancel', on_click=timer.cancel)
  18. @doc.demo('Call a function after a delay', '''
  19. You can call a function after a delay using a timer with the `once` parameter.
  20. ''')
  21. def call_after_delay_demo():
  22. def handle_click():
  23. ui.timer(1.0, lambda: ui.notify('Hi!'), once=True)
  24. ui.button('Notify after 1 second', on_click=handle_click)
  25. @doc.demo("Don't start immediately", '''
  26. By default, the timer will start immediately.
  27. You can change this behavior by setting the `immediate` parameter to `False`.
  28. This will delay the first execution of the callback by the given interval.
  29. ''')
  30. def start_immediately_demo():
  31. from datetime import datetime
  32. label = ui.label()
  33. ui.timer(1.0, lambda: label.set_text(f'{datetime.now():%X}'), immediate=False)
  34. @doc.demo('Global app timer', '''
  35. While `ui.timer` is kind of a UI element that runs in the context of the current page,
  36. you can also use the global `app.timer` for UI-independent timers.
  37. ''')
  38. def app_timer_demo():
  39. from nicegui import app
  40. counter = {'value': 0}
  41. app.timer(1.0, lambda: counter.update(value=counter['value'] + 1))
  42. # @ui.page('/')
  43. def page():
  44. ui.label().bind_text_from(counter, 'value', lambda value: f'Count: {value}')
  45. page() # HIDE
  46. doc.reference(ui.timer)