winit/src/platform_impl/web/web_sys/timeout.rs

41 lines
972 B
Rust
Raw Normal View History

2019-06-25 03:15:34 +02:00
use std::time::Duration;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
2019-06-25 03:15:34 +02:00
#[derive(Debug)]
pub struct Timeout {
handle: i32,
2019-07-01 20:23:42 +02:00
_closure: Closure<dyn FnMut()>,
}
2019-06-25 03:15:34 +02:00
impl Timeout {
pub fn new<F>(f: F, duration: Duration) -> Timeout
where
F: 'static + FnMut(),
{
let window = web_sys::window().expect("Failed to obtain window");
let closure = Closure::wrap(Box::new(f) as Box<dyn FnMut()>);
let handle = window
.set_timeout_with_callback_and_timeout_and_arguments_0(
&closure.as_ref().unchecked_ref(),
duration.as_millis() as i32,
)
.expect("Failed to set timeout");
Timeout {
handle,
_closure: closure,
}
2019-06-25 03:15:34 +02:00
}
}
impl Drop for Timeout {
fn drop(&mut self) {
let window = web_sys::window().expect("Failed to obtain window");
2019-06-25 03:15:34 +02:00
window.clear_timeout_with_handle(self.handle);
}
2019-06-25 03:15:34 +02:00
}