diff --git a/src/timer/global/wasm.rs b/src/timer/global/wasm.rs index d04b0e2..459cbab 100644 --- a/src/timer/global/wasm.rs +++ b/src/timer/global/wasm.rs @@ -22,10 +22,12 @@ pub(crate) fn run() -> TimerHandle { handle } -/// Calls `Window::setTimeout` with the given `Duration`. The callback wakes up the timer and +/// Calls `setTimeout` with the given `Duration`. The callback wakes up the timer and /// processes everything. fn schedule_callback(timer: Arc>, when: Duration) { - let window = web_sys::window().expect("Unable to access Window"); + // Both node and web have `setTimeout` available in their global scope + // so we can treat this as a `Window`. + let window = js_sys::global().unchecked_into::(); let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0( &Closure::once_into_js(move || { let mut timer_lock = timer.lock(); @@ -49,17 +51,12 @@ fn schedule_callback(timer: Arc>, when: Duration) { } // We call `schedule_callback` again for the next event. - let sleep_dur = timer_lock.next_event() - .map(|next_event| { - if next_event > now { - next_event - now - } else { - Duration::new(0, 0) - } - }) - .unwrap_or(Duration::from_secs(5)); - drop(timer_lock); - schedule_callback(timer, sleep_dur); + if let Some(next_event) = timer_lock.next_event() { + if next_event > now { + drop(timer_lock); + schedule_callback(timer.clone(), next_event - now); + } + } }).unchecked_ref(), i32::try_from(when.as_millis()).unwrap_or(0) diff --git a/src/wasm.rs b/src/wasm.rs index 57ee1e6..d187ba8 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -55,11 +55,15 @@ impl Ord for Instant { impl Instant { pub fn now() -> Instant { - let val = web_sys::window() - .expect("not in a browser") - .performance() - .expect("performance object not available") - .now(); + let val = { + use wasm_bindgen::prelude::*; + use wasm_bindgen::JsCast; + js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("performance")) + .expect("failed to get performance from global object") + .unchecked_into::() + .now() + }; + Instant { inner: val } }