1
0

clock.rs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //! A simple little clock that updates the time every few milliseconds.
  2. //!
  3. use async_std::task::sleep;
  4. use dioxus::prelude::*;
  5. use web_time::Instant;
  6. const STYLE: &str = asset!("./examples/assets/clock.css");
  7. fn main() {
  8. dioxus::launch(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 = Instant::now();
  15. loop {
  16. sleep(std::time::Duration::from_millis(27)).await;
  17. // Update the time, using a more precise approach of getting the duration since we started the timer
  18. millis.set(start.elapsed().as_millis() as i64);
  19. }
  20. });
  21. // Format the time as a string
  22. // This is rather cheap so it's fine to leave it in the render function
  23. let time = format!(
  24. "{:02}:{:02}:{:03}",
  25. millis() / 1000 / 60 % 60,
  26. millis() / 1000 % 60,
  27. millis() % 1000
  28. );
  29. rsx! {
  30. document::Link { rel: "stylesheet", href: STYLE }
  31. div { id: "app",
  32. div { id: "title", "Carpe diem 🎉" }
  33. div { id: "clock-display", "{time}" }
  34. }
  35. }
  36. }