Instant

If you call std::time::Instant::now() on a WASM platform, it will panic. This crate provides a partial replacement for std::time::Instant that works on WASM too. This defines the type instant::Instant which is:

Note that even if the stdweb or wasm-bindgen feature is enabled, this crate will continue to rely on std::time::Instant as long as you are not targeting wasm32. This allows for portable code that will work on both native and WASM platforms.

The feature now.

By enabling the feature now the function instant::now() will be exported and will either:

The result is expressed in milliseconds.

Examples

Using instant for a native platform.

Cargo.toml: toml [dependencies] instant = "0.1"

main.rs: rust fn main() { // Will be the same as `std::time::Instant`. let now = instant::Instant::new(); }


Using instant for a WASM platform.

This example shows the use of the stdweb feature. It would be similar with wasm-bindgen.

Cargo.toml: toml [dependencies] instant = { version = "0.1", features = [ "stdweb" ] }

main.rs: rust fn main() { // Will emulate `std::time::Instant` based on `performance.now()`. let now = instant::Instant::new(); }


Using instant for a WASM platform where performance.now() is not available.

This example shows the use of the inaccurate feature.

Cargo.toml: toml [dependencies] instant = { version = "0.1", features = [ "wasm-bindgen", "inaccurate" ] }

main.rs: rust fn main() { // Will emulate `std::time::Instant` based on `Date.now()`. let now = instant::Instant::new(); }


Using instant for any platform enabling a feature transitively.

Cargo.toml: ```toml [features] stdweb = [ "instant/stdweb" ] wasm-bindgen = [ "instant/wasm-bindgen" ]

[dependencies] instant = "0.1" ```

lib.rs: rust fn my_function() { // Will select the proper implementation depending on the // feature selected by the user. let now = instant::Instant::new(); }


Using the feature now.

Cargo.toml: ```toml [features] stdweb = [ "instant/stdweb" ] wasm-bindgen = [ "instant/wasm-bindgen" ]

[dependencies] instant = { version = "0.1", features = [ "now" ] } ```

lib.rs: rust fn my_function() { // Will select the proper implementation depending on the // feature selected by the user. let now_instant = instant::Instant::new(); let now_milliseconds = instant::now(); // In milliseconds. }

Using the feature now without stdweb or wasm-bindgen.

Cargo.toml: toml [dependencies] instant = { version = "0.", features = [ "now" ] }

lib.rs: rust fn my_function() { // Will use the 'now' javascript implementation. let now_instant = instant::Instant::new(); let now_milliseconds = instant::now(); // In milliseconds. }

javascript WASM bindings file: js function now() { return Date.now() / 1000.0; }