1.0.2 • Published 4 years ago

@bradgarropy/use-timer v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

⏱ useTimer

version downloads size github actions coverage typescript contributing contributors discord

React hook implementation of a stopwatch. Featured in MURPHY.

📦 Installation

This package is hosted on npm.

npm install @bradgarropy/use-timer

🥑 Usage

Import the useTimer hook in any React component, then call it to receive a timer that holds the state and functions which implement a stopwatch.

import useTimer from "@bradgarropy/use-timer"

const App = () => {
    const timer = useTimer()

    timer.start()

    timer.lap()
    timer.lap()
    timer.lap()

    timer.stop()

    console.log(timer.elapsedTime)
    // 3000

    console.log(timer.laps)
    // [
    //   {start: 0, end: 1000, time: 1000},
    //   {start: 1000, end: 2000, time: 1000},
    //   {start: 2000, end: 3000, time: 1000}
    // ]

    timer.reset()
}

📖 API Reference

useTimer()

Instantiates a timer, which updates with the latest values. No arguments are required. The hook returns an object with everything needed to implement a stopwatch.

NameTypeExampleDescription
isActivebooleanfalseIndicates that the timer is active, either running or paused.
isInactivebooleantrueIndicates that the timer is inactive, and hasn't been started.
isRunningbooleanfalseIndicates if the timer is running.
isPausedbooleanfalseIndicates if the timer is paused.
elapsedTimenumber0Total time in milliseconds.
lapsobject[]Array of laps.
startfunctionfunctionStarts the timer.
stopfunctionfunctionPauses the timer.
resetfunctionfunctionResets the timer.
lapfunctionfunctionAdds a new lap.

The elapsedTime is expressed in milliseconds, and has a resolution of 10ms.

Each of the control functions are ignored in certain situations.

  • start does nothing if the timer is already running.
  • stop does nothing if the timer is already paused.
  • reset does nothing if the timer is inactive.
  • lap does nothing if the timer is paused.

❔ Questions

🐛 report bugs by filing issues
📢 provide feedback with issues or on twitter
🙋🏼‍♂️ use my ama or twitter to ask any other questions

✨ contributors