Skip to content

Commit 5cf8eed

Browse files
committed
gloo-timers: Use raw bindings to (set|clear)(Timeout|Interval) instead of the Window API, since window isn't always present (e.g Web Workers)
1 parent b3316ef commit 5cf8eed

File tree

2 files changed

+25
-17
lines changed

2 files changed

+25
-17
lines changed

crates/timers/src/callback.rs

+11-15
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Callback-style timer APIs.
22
3-
use super::window;
3+
use super::{clear_interval, clear_timeout, set_interval, set_timeout};
44
use std::fmt;
55
use wasm_bindgen::prelude::*;
66
use wasm_bindgen::JsCast;
@@ -20,7 +20,7 @@ pub struct Timeout {
2020
impl Drop for Timeout {
2121
fn drop(&mut self) {
2222
if let Some(id) = self.id {
23-
window().clear_timeout_with_handle(id);
23+
clear_timeout(id);
2424
}
2525
}
2626
}
@@ -50,12 +50,10 @@ impl Timeout {
5050
{
5151
let closure = Closure::once(callback);
5252

53-
let id = window()
54-
.set_timeout_with_callback_and_timeout_and_arguments_0(
55-
closure.as_ref().unchecked_ref::<js_sys::Function>(),
56-
millis as i32,
57-
)
58-
.unwrap_throw();
53+
let id = set_timeout(
54+
closure.as_ref().unchecked_ref::<js_sys::Function>(),
55+
millis as i32,
56+
);
5957

6058
Timeout {
6159
id: Some(id),
@@ -125,7 +123,7 @@ pub struct Interval {
125123
impl Drop for Interval {
126124
fn drop(&mut self) {
127125
if let Some(id) = self.id {
128-
window().clear_interval_with_handle(id);
126+
clear_interval(id);
129127
}
130128
}
131129
}
@@ -158,12 +156,10 @@ impl Interval {
158156
callback();
159157
}) as Box<FnMut()>);
160158

161-
let id = window()
162-
.set_interval_with_callback_and_timeout_and_arguments_0(
163-
closure.as_ref().unchecked_ref::<js_sys::Function>(),
164-
millis as i32,
165-
)
166-
.unwrap_throw();
159+
let id = set_interval(
160+
closure.as_ref().unchecked_ref::<js_sys::Function>(),
161+
millis as i32,
162+
);
167163

168164
Interval {
169165
id: Some(id),

crates/timers/src/lib.rs

+14-2
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,22 @@ TODO
6767
#[cfg(feature = "futures")]
6868
extern crate futures_rs as futures;
6969

70+
use js_sys::Function;
7071
use wasm_bindgen::prelude::*;
7172

72-
fn window() -> web_sys::Window {
73-
web_sys::window().unwrap_throw()
73+
#[wasm_bindgen]
74+
extern "C" {
75+
#[wasm_bindgen(js_name = "setTimeout")]
76+
pub fn set_timeout(handler: &Function, timeout: i32) -> i32;
77+
78+
#[wasm_bindgen(js_name = "clearTimeout")]
79+
pub fn clear_timeout(token: i32);
80+
81+
#[wasm_bindgen(js_name = "setInterval")]
82+
pub fn set_interval(handler: &Function, timeout: i32) -> i32;
83+
84+
#[wasm_bindgen(js_name = "clearInterval")]
85+
pub fn clear_interval(token: i32);
7486
}
7587

7688
pub mod callback;

0 commit comments

Comments
 (0)