clock.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. //! A simple little clock that updates the time every few milliseconds.
  2. //!
  3. //! Neither Rust nor Tokio have an interval function, so we just sleep until the next update.
  4. //! Tokio timer's don't work on WASM though, so you'll need to use a slightly different approach if you're targeting the web.
  5. use dioxus::prelude::*;
  6. const STYLE: &str = asset!("./examples/assets/clock.css");
  7. fn main() {
  8. launch_desktop(app);
  9. }
  10. fn app() -> Element {
  11. let mut millis = use_signal(|| 0);
  12. use_future(move || async move {
  13. // Save our initial timea
  14. let start = std::time::Instant::now();
  15. loop {
  16. // In lieu of an interval, we just sleep until the next update
  17. let now = tokio::time::Instant::now();
  18. tokio::time::sleep_until(now + std::time::Duration::from_millis(27)).await;
  19. // Update the time, using a more precise approach of getting the duration since we started the timer
  20. millis.set(start.elapsed().as_millis() as i64);
  21. }
  22. });
  23. // Format the time as a string
  24. // This is rather cheap so it's fine to leave it in the render function
  25. let time = format!(
  26. "{:02}:{:02}:{:03}",
  27. millis() / 1000 / 60 % 60,
  28. millis() / 1000 % 60,
  29. millis() % 1000
  30. );
  31. rsx! {
  32. head::Link { rel: "stylesheet", href: STYLE }
  33. div { id: "app",
  34. div { id: "title", "Carpe diem 🎉" }
  35. div { id: "clock-display", "{time}" }
  36. }
  37. }
  38. }