clock.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. fn main() {
  7. launch_desktop(app);
  8. }
  9. fn app() -> Element {
  10. let mut millis = use_signal(|| 0);
  11. use_future(move || async move {
  12. // Save our initial timea
  13. let start = std::time::Instant::now();
  14. loop {
  15. // In lieu of an interval, we just sleep until the next update
  16. let now = tokio::time::Instant::now();
  17. tokio::time::sleep_until(now + std::time::Duration::from_millis(27)).await;
  18. // Update the time, using a more precise approach of getting the duration since we started the timer
  19. millis.set(start.elapsed().as_millis() as i64);
  20. }
  21. });
  22. // Format the time as a string
  23. // This is rather cheap so it's fine to leave it in the render function
  24. let time = format!(
  25. "{:02}:{:02}:{:03}",
  26. millis() / 1000 / 60 % 60,
  27. millis() / 1000 % 60,
  28. millis() % 1000
  29. );
  30. rsx! {
  31. style { {include_str!("./assets/clock.css")} }
  32. div { id: "app",
  33. div { id: "title", "Carpe diem 🎉" }
  34. div { id: "clock-display", "{time}" }
  35. }
  36. }
  37. }