from typing import Callable
import solara
import solara.lab
import time
def use_interval(f: Callable, interval: float = 10.0, enabled=True):
"""
Call a function periodically.
Parameters
----------
f
Function to call periodically.
interval
Interval in milliseconds.
"""
def run():
if enabled:
time_start = time.time()
next_tick = time_start + interval
while True:
# instead of sleeping for 1 second, we sleep until the next second
# this takes into account overhead and makes the timer more accurate
f()
time.sleep(max(0, next_tick - time.time()))
next_tick += interval
return solara.use_thread(run, dependencies=[interval, enabled])
@solara.component
def Page():
router = solara.use_router()
count = solara.use_reactive(5)
cancelled = solara.use_reactive(False)
def redirect():
router.push(f"/some_url")
def count_down():
if count.value > 0:
count.value -= 1
else:
redirect()
use_interval(count_down, interval=1, enabled=not cancelled.value)
solara.lab.ConfirmationDialog(
not cancelled.value,
on_cancel=lambda: cancelled.set(True),
on_ok=lambda: redirect(),
title="Redirecting",
content=f"Redirecting in {count.value+1} seconds",
)
if cancelled.value:
solara.Button("Redirect anyway", on_click=redirect)