Simple timer turned into React Hooks. Read about Hooks feature.
npm i use-timer
With Yarn:
yarn add use-timer
🚀 Try demo here: https://stackblitz.com/edit/use-timer.
import React from 'react';
import { useTimer } from 'use-timer';
const App = () => {
const { time, start, pause, reset, isRunning } = useTimer();
return (
<>
<div>
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
<button onClick={reset}>Reset</button>
</div>
<p>Elapsed time: {time}</p>
{isRunning && <p>Running...</p>}
</>
);
};
const { time, start, pause, reset, isRunning } = useTimer({
initialTime: 100,
timerType: 'DECREMENTAL',
});
const { time, start, pause, reset, isRunning } = useTimer({
endTime: 30,
initialTime: 10,
});
Some callback functions can be provided.
const { time, start, pause, reset, isRunning } = useTimer({
endTime,
onTimeOver: () => {
console.log('Time is over');
},
});
const { time, start, pause, reset, isRunning } = useTimer({
endTime,
onTimeUpdate: time => {
console.log('Time is updated', time);
},
});
The configuration and all its parameters are optional.
Property | Type | Default value | Description |
---|---|---|---|
endTime | number | null | The value for which timer stops |
initialTime | number | 0 | The starting value for the timer |
interval | number | 1000 | The interval in milliseconds |
onTimeOver | function | Callback function that is called when time is over | |
onTimeUpdate | function | Callback function that is called when time is updated | |
step | number | 1 | the value to add to each increment / decrement |
timerType | string | "INCREMENTAL" | the choice between a value that increases ("INCREMENTAL") or decreases ("DECREMENTAL") |