Przeglądaj źródła

make timer.interval a bindable property

Falko Schindler 2 lat temu
rodzic
commit
702eff721d
1 zmienionych plików z 7 dodań i 5 usunięć
  1. 7 5
      nicegui/timer.py

+ 7 - 5
nicegui/timer.py

@@ -16,6 +16,7 @@ class Timer:
     prepared_coroutines: List[NamedCoroutine] = []
 
     active = BindableProperty()
+    interval = BindableProperty()
 
     def __init__(self, interval: float, callback: Callable, *, active: bool = True, once: bool = False):
         """Timer
@@ -24,14 +25,15 @@ class Timer:
         A timer will execute a callback repeatedly with a given interval.
         The parent view container will be updated automatically, as long as the callback does not return `False`.
 
-        :param interval: the interval in which the timer is called
+        :param interval: the interval in which the timer is called (can be changed during runtime)
         :param callback: function or coroutine to execute when interval elapses (can return `False` to prevent view update)
-        :param active: whether the callback should be executed or not
+        :param active: whether the callback should be executed or not (can be changed during runtime)
         :param once: whether the callback is only executed once after a delay specified by `interval` (default: `False`)
         """
 
         parent = view_stack[-1]
         self.active = active
+        self.interval = interval
 
         async def do_callback():
             try:
@@ -43,7 +45,7 @@ class Timer:
                 traceback.print_exc()
 
         async def timeout():
-            await asyncio.sleep(interval)
+            await asyncio.sleep(self.interval)
             await do_callback()
             await parent.update()
 
@@ -56,12 +58,12 @@ class Timer:
                         if needs_update != False:
                             await parent.update()
                     dt = time.time() - start
-                    await asyncio.sleep(interval - dt)
+                    await asyncio.sleep(self.interval - dt)
                 except asyncio.CancelledError:
                     return
                 except:
                     traceback.print_exc()
-                    await asyncio.sleep(interval)
+                    await asyncio.sleep(self.interval)
 
         coroutine = timeout() if once else loop()
         event_loop = asyncio.get_event_loop()