1use crate::dom::window;
2use std::rc::Rc;
3use wasm_bindgen::closure::Closure;
4use wasm_bindgen::{JsCast, JsValue};
5
6#[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
20pub 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}