https://github.com/barelyhuman/background-timer
React hook to run a timer in the background
https://github.com/barelyhuman/background-timer
Last synced: 2 months ago
JSON representation
React hook to run a timer in the background
- Host: GitHub
- URL: https://github.com/barelyhuman/background-timer
- Owner: barelyhuman
- License: mit
- Created: 2020-12-01T18:54:22.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2020-12-29T13:34:56.000Z (over 4 years ago)
- Last Synced: 2025-03-28T13:44:46.619Z (3 months ago)
- Language: TypeScript
- Homepage:
- Size: 427 KB
- Stars: 4
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# background-timer
Simple react hook to run a timer in the background
## Motivation
Nothing really, pulled it off a project I wrote it for and now it's a package.
## Install
```sh
npm i @barelyreaper/background-timer
```## Usage
### On Render Timer
Used when the timer is **not** dependant on some other property and can be run as soon as the page/component is rendered (example OTP validation screens)
```js
import { useBackgroundTimer, msTimestamp } from 'background-timer';export default function App() {
/**
* @param milliseconds
* @returns {timer: milliseconds, reset: function} resets the timer
*/const { timer, reset } = useBackgroundTimer(2 * 1000 * 60, {
onTimerEnd: () => {
alert('Timer Ended');
},
});return (
<>
{msTimestamp(timer)}
0} onClick={() => reset()}>
Reset Timer
>
);
}
```### Manually Control timer trigger
Used when the timer is dependant on some other property that might not be available during app render (example: Booking lock-in dependency)
```js
import { msTimestamp, useManualTimer } from '@barelyreaper/background-timer';
import './App.css';function App() {
/**
* @param ticker delay provided to the internal interval, 1000 means timer executes every 1 second
* @param options={onTimerEnd?:function} optional options object that allows adding a callback on timer end
* @returns {timer: milliseconds, startTimer: function(millisecondsToExecFor){},stopTimer:function,stopped:Boolean}
*/const { startTimer, stopTimer, timer, stopped } = useManualTimer(1000, {
onTimerEnd: () => {
alert('Timer Ended');
},
});return (
Manual Timer
{msTimestamp(timer)}
startTimer(2 * 10 * 1000)}>
{timer > 0 ? 'Reset Timer' : 'Start Timer'}
stopTimer()}
>
Stop Timer
);
}export default App;
```