clock.rs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. fn main() {
  7. dioxus::launch(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 = Instant::now();
  14. loop {
  15. sleep(std::time::Duration::from_millis(27)).await;
  16. // Update the time, using a more precise approach of getting the duration since we started the timer
  17. millis.set(start.elapsed().as_millis() as i64);
  18. }
  19. });
  20. // Format the time as a string
  21. // This is rather cheap so it's fine to leave it in the render function
  22. let time = format!(
  23. "{:02}:{:02}:{:03}",
  24. millis() / 1000 / 60 % 60,
  25. millis() / 1000 % 60,
  26. millis() % 1000
  27. );
  28. rsx! {
  29. document::Stylesheet { href: asset!("/examples/assets/clock.css") }
  30. div { id: "app",
  31. div { id: "title", "Carpe diem 🎉" }
  32. div { id: "clock-display", "{time}" }
  33. }
  34. }
  35. }