gloo_console/
counter.rs

1//! The `console.count` and `console.countReset` functions allow you to run a counter
2//! amd log it to the browser's developer tools console. You
3//! call `console.count("foo")` when the counter begins, and call
4//! `console.countReset("foo")` when it is to be reset.
5//!
6//! [See MDN for more info](https://developer.mozilla.org/en-US/docs/Web/API/Console/count).
7//!
8//! This API wraps both the `count` and `countReset` calls into a single type
9//! named `Counter`, ensuring both are called.
10//!
11//! The counter is started with
12//!
13//! ```no_run
14//! use gloo_console::Counter;
15//!
16//! let counter = Counter::new("foo");
17//!
18//! counter.count();
19//! counter.count();
20//! ```
21
22use web_sys::console;
23
24/// A console time measurement.
25///
26/// Dropping this will reset the counter to 0.
27#[derive(Debug)]
28pub struct Counter<'a> {
29    label: &'a str,
30}
31
32impl<'a> Counter<'a> {
33    /// Starts a console time measurement. The measurement
34    /// ends when the constructed `ConsoleTimer` object is dropped.
35    ///
36    /// # Example
37    ///
38    /// ```no_run
39    /// use gloo_console::Counter;
40    ///
41    /// let _timer = Counter::new("foo");
42    /// ```
43    pub fn new(label: &'a str) -> Counter<'a> {
44        console::count_with_label(label);
45        Counter { label }
46    }
47
48    /// Increments the counter
49    pub fn count(&self) {
50        console::count_with_label(self.label);
51    }
52}
53
54impl<'a> Drop for Counter<'a> {
55    fn drop(&mut self) {
56        console::count_reset_with_label(self.label);
57    }
58}