Guest User

Request Animation frame web_sys 0.3

a guest
Jun 13th, 2026
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.39 KB | Software | 0 0
  1. use wasm_bindgen::JsCast;
  2. use wasm_bindgen::closure::Closure;
  3. use web_sys::{Document, HtmlCanvasElement, HtmlElement, Window};
  4.  
  5.  
  6. fn window() -> Window {
  7.     web_sys::window().expect("no global `window` exists")
  8. }
  9.  
  10. fn document() -> Document {
  11.     window()
  12.         .document()
  13.         .expect("should have a document on window")
  14. }
  15.  
  16. fn body() -> HtmlElement {
  17.     document().body().expect("document should have a body")
  18. }
  19.  
  20. fn request_animation_frame(f: &Closure<dyn FnMut()>) {
  21.     window()
  22.         .request_animation_frame(f.as_ref().unchecked_ref())
  23.         .expect("should register `requestAnimationFrame` OK");
  24. }
  25.  
  26. fn foo() {
  27.  
  28.         web_sys::console::log_1(&"hello wasm".into());
  29.  
  30.         let f: Rc<RefCell<Option<Closure<dyn FnMut()>>>> = Rc::new(RefCell::new(None));
  31.         let g = f.clone();
  32.         let h = g.clone();
  33.  
  34.         let mut i = 0;
  35.         let closure = Closure::wrap(Box::new(move || {
  36.             if i > 300 {
  37.                 body().set_text_content(Some("All done!"));
  38.                 return;
  39.             }
  40.  
  41.             // Set the body's text content to how many times this
  42.             // requestAnimationFrame callback has fired.
  43.             i += 1;
  44.             request_animation_frame(h.borrow().as_ref().unwrap());
  45.         }) as Box<dyn FnMut()>);
  46.         *g.borrow_mut() = Some(closure);
  47.  
  48.         request_animation_frame(f.borrow().as_ref().unwrap());
  49. }
Advertisement
Add Comment
Please, Sign In to add comment