Skip to content

Instantly share code, notes, and snippets.

@xxshady
Last active June 17, 2024 22:41
Show Gist options
  • Save xxshady/78603bc703ba74eb65799414391b60ee to your computer and use it in GitHub Desktop.
Save xxshady/78603bc703ba74eb65799414391b60ee to your computer and use it in GitHub Desktop.
Simple WASM wait/sleep implementation
use crate::timers::set_timeout;
use std::{
future::{poll_fn, Future},
task::Poll,
};
use web_time::{Duration, SystemTime};
pub fn wait(duration: Duration) -> impl Future {
let dest = SystemTime::now() + duration;
let mut timer_was_set = false;
poll_fn(move |cx| {
if SystemTime::now() >= dest {
return Poll::Ready(());
}
if timer_was_set {
return Poll::Pending;
}
timer_was_set = true;
let waker = cx.waker().clone();
// see my timers gist
set_timeout(
Box::new(|| {
waker.wake();
}),
duration,
);
Poll::Pending
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment