Simple timer turned into React Hooks. Read about Hooks feature.
npm i use-timer --save
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 } = useTimer();
return (
<React.Fragment>
<div>
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
<button onClick={reset}>Reset</button>
</div>
<p>Elapsed time: {time}</p>
</React.Fragment>
);
};
import React from 'react';
import { useTimer } from 'use-timer';
const App = () => {
const { time, start, pause, reset } = useTimer({
initialTime: 100,
timerType: 'DECREMENTAL',
});
return (
<React.Fragment>
<div>
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
<button onClick={reset}>Reset</button>
</div>
<p>Remaining time: {time}</p>
</React.Fragment>
);
};
import React from 'react';
import { useTimer } from 'use-timer';
const App = () => {
const { time, start, pause, reset } = useTimer({
endTime: 30,
initialTime: 10,
});
return (
<React.Fragment>
<div>
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
<button onClick={reset}>Reset</button>
</div>
<p>Ellapsed time: {time}</p>
</React.Fragment>
);
};
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 |
timerType | string | "INCREMENTAL" | the choice between a value that increases ("INCREMENTAL") or decreases ("DECREMENTAL") |