Skip to content

Commit

Permalink
Add sleep. (#163)
Browse files Browse the repository at this point in the history
* Add sleep.

* Fix a typo.
  • Loading branch information
futursolo authored Oct 31, 2021
1 parent 5b67085 commit a99fcbd
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions crates/timers/src/future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ use crate::callback::{Interval, Timeout};

use futures_channel::{mpsc, oneshot};
use futures_core::stream::Stream;
use std::convert::TryFrom;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use wasm_bindgen::prelude::*;

/// A scheduled timeout as a `Future`.
Expand Down Expand Up @@ -73,6 +75,28 @@ impl TimeoutFuture {
}
}

/// Waits until the specified duration has elapsed.
///
/// # Panics
///
/// This function will panic if the specified [`Duration`] cannot be casted into a u32 in
/// milliseconds.
///
/// # Example
///
/// ```no_run
/// use std::time::Duration;
/// use gloo_timers::future::sleep;
///
/// sleep(Duration::from_secs(1)).await;
/// ```
pub fn sleep(dur: Duration) -> TimeoutFuture {
let millis = u32::try_from(dur.as_millis())
.expect_throw("failed to cast the duration into a u32 with Duration::as_millis.");

TimeoutFuture::new(millis)
}

impl Future for TimeoutFuture {
type Output = ();

Expand Down

0 comments on commit a99fcbd

Please sign in to comment.