1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use super::{to_ms, Task};
use crate::callback::Callback;
use std::time::Duration;
use stdweb::Value;
#[allow(unused_imports)]
use stdweb::{_js_impl, js};
#[must_use]
pub struct TimeoutTask(Option<Value>);
#[derive(Default)]
pub struct TimeoutService {}
impl TimeoutService {
pub fn new() -> Self {
Self {}
}
pub fn spawn(&mut self, duration: Duration, callback: Callback<()>) -> TimeoutTask {
let callback = move || {
callback.emit(());
};
let ms = to_ms(duration);
let handle = js! {
var callback = @{callback};
var action = function() {
callback();
callback.drop();
};
var delay = @{ms};
return {
timeout_id: setTimeout(action, delay),
callback: callback,
};
};
TimeoutTask(Some(handle))
}
}
impl Task for TimeoutTask {
fn is_active(&self) -> bool {
self.0.is_some()
}
fn cancel(&mut self) {
let handle = self.0.take().expect("tried to cancel timeout twice");
js! { @(no_return)
var handle = @{handle};
clearTimeout(handle.timeout_id);
handle.callback.drop();
}
}
}
impl Drop for TimeoutTask {
fn drop(&mut self) {
if self.is_active() {
self.cancel();
}
}
}