clock.rs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //! A simple little clock that updates the time every few milliseconds.
  2. use async_std::task::sleep;
  3. use dioxus::prelude::*;
  4. use web_time::Instant;
  5. fn main() {
  6. dioxus::launch(app);
  7. }
  8. fn app() -> Element {
  9. let mut millis = use_signal(|| 0);
  10. use_future(move || async move {
  11. // Save our initial timea
  12. let start = Instant::now();
  13. loop {
  14. sleep(std::time::Duration::from_millis(27)).await;
  15. // Update the time, using a more precise approach of getting the duration since we started the timer
  16. millis.set(start.elapsed().as_millis() as i64);
  17. }
  18. });
  19. // Format the time as a string
  20. // This is rather cheap so it's fine to leave it in the render function
  21. let time = format!(
  22. "{:02}:{:02}:{:03}",
  23. millis() / 1000 / 60 % 60,
  24. millis() / 1000 % 60,
  25. millis() % 1000
  26. );
  27. rsx! {
  28. document::Stylesheet { href: asset!("/examples/assets/clock.css") }
  29. div { id: "app",
  30. div { id: "title", "Carpe diem 🎉" }
  31. div { id: "clock-display", "{time}" }
  32. }
  33. }
  34. }