Last active
January 19, 2025 12:45
-
-
Save xxshady/78603bc703ba74eb65799414391b60ee to your computer and use it in GitHub Desktop.
Simple (not) WASM wait/sleep implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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