timer_documentation.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. *Added in version 2.9.0*
  30. ''')
  31. def start_immediately_demo():
  32. from datetime import datetime
  33. label = ui.label()
  34. ui.timer(1.0, lambda: label.set_text(f'{datetime.now():%X}'), immediate=False)
  35. @doc.demo('Global app timer', '''
  36. While `ui.timer` is kind of a UI element that runs in the context of the current page,
  37. you can also use the global `app.timer` for UI-independent timers.
  38. *Added in version 2.9.0*
  39. ''')
  40. def app_timer_demo():
  41. from nicegui import app
  42. counter = {'value': 0}
  43. app.timer(1.0, lambda: counter.update(value=counter['value'] + 1))
  44. # @ui.page('/')
  45. def page():
  46. ui.label().bind_text_from(counter, 'value', lambda value: f'Count: {value}')
  47. page() # HIDE
  48. doc.reference(ui.timer)