use super::sys::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
#[derive(Debug)]
#[must_use = "timeouts cancel on drop; either call `forget` or `drop` explicitly"]
pub struct Timeout {
id: Option<i32>,
closure: Option<Closure<FnMut()>>,
}
impl Drop for Timeout {
fn drop(&mut self) {
if let Some(id) = self.id {
clear_timeout(id);
}
}
}
impl Timeout {
pub fn new<F>(millis: u32, callback: F) -> Timeout
where
F: 'static + FnOnce(),
{
let closure = Closure::once(callback);
let id = set_timeout(
closure.as_ref().unchecked_ref::<js_sys::Function>(),
millis as i32,
);
Timeout {
id: Some(id),
closure: Some(closure),
}
}
pub fn forget(mut self) -> i32 {
let id = self.id.take().unwrap_throw();
self.closure.take().unwrap_throw().forget();
id
}
pub fn cancel(mut self) -> Closure<FnMut()> {
self.closure.take().unwrap_throw()
}
}
#[derive(Debug)]
#[must_use = "intervals cancel on drop; either call `forget` or `drop` explicitly"]
pub struct Interval {
id: Option<i32>,
closure: Option<Closure<FnMut()>>,
}
impl Drop for Interval {
fn drop(&mut self) {
if let Some(id) = self.id {
clear_interval(id);
}
}
}
impl Interval {
pub fn new<F>(millis: u32, callback: F) -> Interval
where
F: 'static + FnMut(),
{
let closure = Closure::wrap(Box::new(callback) as Box<FnMut()>);
let id = set_interval(
closure.as_ref().unchecked_ref::<js_sys::Function>(),
millis as i32,
);
Interval {
id: Some(id),
closure: Some(closure),
}
}
pub fn forget(mut self) -> i32 {
let id = self.id.take().unwrap_throw();
self.closure.take().unwrap_throw().forget();
id
}
pub fn cancel(mut self) -> Closure<FnMut()> {
self.closure.take().unwrap_throw()
}
}