sauron_core/dom/
raf.rs

1use crate::dom::window;
2use std::rc::Rc;
3use wasm_bindgen::closure::Closure;
4use wasm_bindgen::{JsCast, JsValue};
5
6/// request animation frame handle
7#[derive(Clone)]
8pub struct AnimationFrameHandle {
9    handle: i32,
10    _closure: Rc<Closure<dyn FnMut()>>,
11}
12impl Drop for AnimationFrameHandle {
13    fn drop(&mut self) {
14        window()
15            .cancel_animation_frame(self.handle)
16            .expect("cancel animation handle")
17    }
18}
19
20/// utility function which a closure in request animation frame
21pub fn request_animation_frame<F>(f: F) -> Result<AnimationFrameHandle, JsValue>
22where
23    F: FnMut() + 'static,
24{
25    let closure: Closure<dyn FnMut() + 'static> = Closure::once(f);
26    let handle = window().request_animation_frame(closure.as_ref().unchecked_ref())?;
27    Ok(AnimationFrameHandle {
28        handle,
29        _closure: Rc::new(closure),
30    })
31}