Skip to content

Commit 1018d35

Browse files
committed
fix: clearTimeout illegal invocation in browser (#187)
1 parent 8cf3724 commit 1018d35

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

crates/timers/src/callback.rs

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,19 @@ use wasm_bindgen::{JsCast, JsValue};
66

77
#[wasm_bindgen]
88
extern "C" {
9-
#[wasm_bindgen(js_name = "setTimeout", catch)]
10-
fn set_timeout(handler: &Function, timeout: i32) -> Result<i32, JsValue>;
9+
type GlobalThis;
1110

12-
#[wasm_bindgen(js_name = "setInterval", catch)]
13-
fn set_interval(handler: &Function, timeout: i32) -> Result<i32, JsValue>;
11+
#[wasm_bindgen(method, js_name = "setTimeout", catch)]
12+
fn set_timeout(this: &GlobalThis, handler: &Function, timeout: i32) -> Result<i32, JsValue>;
1413

15-
#[wasm_bindgen(js_name = "clearTimeout")]
16-
fn clear_timeout(handle: i32);
14+
#[wasm_bindgen(method, js_name = "setInterval", catch)]
15+
fn set_interval(this: &GlobalThis, handler: &Function, timeout: i32) -> Result<i32, JsValue>;
1716

18-
#[wasm_bindgen(js_name = "clearInterval")]
19-
fn clear_interval(handle: i32);
17+
#[wasm_bindgen(method, js_name = "clearTimeout")]
18+
fn clear_timeout(this: &GlobalThis, handle: i32);
19+
20+
#[wasm_bindgen(method, js_name = "clearInterval")]
21+
fn clear_interval(this: &GlobalThis, handle: i32);
2022
}
2123

2224
/// A scheduled timeout.
@@ -37,7 +39,8 @@ impl Drop for Timeout {
3739
/// `clearTimeout` directly.
3840
fn drop(&mut self) {
3941
if let Some(id) = self.id {
40-
clear_timeout(id);
42+
let global = js_sys::global().unchecked_into::<GlobalThis>();
43+
global.clear_timeout(id);
4144
}
4245
}
4346
}
@@ -61,7 +64,8 @@ impl Timeout {
6164
{
6265
let closure = Closure::once(callback);
6366

64-
let id = set_timeout(
67+
let global = js_sys::global().unchecked_into::<GlobalThis>();
68+
let id = global.set_timeout(
6569
closure.as_ref().unchecked_ref::<js_sys::Function>(),
6670
millis as i32,
6771
)
@@ -139,7 +143,8 @@ impl Drop for Interval {
139143
/// `clearInterval` directly.
140144
fn drop(&mut self) {
141145
if let Some(id) = self.id {
142-
clear_interval(id);
146+
let global = js_sys::global().unchecked_into::<GlobalThis>();
147+
global.clear_interval(id);
143148
}
144149
}
145150
}
@@ -162,7 +167,8 @@ impl Interval {
162167
{
163168
let closure = Closure::wrap(Box::new(callback) as Box<dyn FnMut()>);
164169

165-
let id = set_interval(
170+
let global = js_sys::global().unchecked_into::<GlobalThis>();
171+
let id = global.set_interval(
166172
closure.as_ref().unchecked_ref::<js_sys::Function>(),
167173
millis as i32,
168174
)

0 commit comments

Comments
 (0)