Skip to content

Use js_sys to enable node.js compatibility #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 10 additions & 13 deletions src/timer/global/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Mutex<Timer>>, 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::<web_sys::Window>();
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(
&Closure::once_into_js(move || {
let mut timer_lock = timer.lock();
Expand All @@ -49,17 +51,12 @@ fn schedule_callback(timer: Arc<Mutex<Timer>>, 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)
Expand Down
14 changes: 9 additions & 5 deletions src/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<web_sys::Performance>()
.now()
};

Instant { inner: val }
}

Expand Down