Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-timer-hook",
"version": "1.0.8",
"version": "1.1.0",
"description": "React timer hook is a custom react hook built to handle timers and count down logic in your react component.",
"main": "dist/index.js",
"scripts": {
Expand Down
127 changes: 105 additions & 22 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
## react-timer-hook

React timer hook is a custom [react hook](https://reactjs.org/docs/hooks-intro.html), built to handle timers and countdown logic in your react component.
React timer hook is a custom [react hook](https://reactjs.org/docs/hooks-intro.html), built to handle time related logic in your react component:

1. Timers (countdown timer) `useTimer`
2. Stopwatch (count up timer) `useStopwatch`


#### Note:

Expand All @@ -18,58 +22,137 @@ OR

---

## Example
## `useTimer`

### Example

```javascript
import React from 'react';
import useTimer from 'react-timer-hook';
import { useTimer } from 'react-timer-hook';

export default function App() {
function MyTimer({ expiryTimestamp }) {
const {
seconds,
minutes,
hours,
days,
startTimer,
stopTimer,
resetTimer,
} = useTimer({ autoStart: true });
start,
pause,
resume
} = useTimer({ expiryTimestamp, onExpire: () => console.warn('onExpire called') });


return (
<div style={{textAlign: 'center'}}>
<h1>react-timer-hook Demo</h1>
<h1>react-timer-hook </h1>
<p>Timer Demo</p>
<div style={{fontSize: '100px'}}>
<span>{days}</span>:<span>{hours}</span>:<span>{minutes}</span>:<span>{seconds}</span>
</div>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
<button onClick={resetTimer}>Reset</button>
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
<button onClick={resume}>Resume</button>
</div>
);
}
```

---
export default function App() {
var t = new Date();
t.setSeconds(t.getSeconds() + 600); // 10 minutes timer
return (
<div>
<MyTimer expiryTimestamp={t} />
</div>
);
}
```

## Settings
### Settings

| key | Type | Required | Description |
| --- | --- | --- | ---- |
| autoStart | boolean | No | if set to `true` timer will auto start |
| expiryTimestamp | number(timestamp) | No | if set a countdown timer will start, instead of normal timer |
| onExpire | Function | No | callback function to be executed once countdown timer is expired, works only for countdown |
| expiryTimestamp | number(timestamp) | YES | this will define for how long the timer will be running |
| onExpire | Function | No | callback function to be executed once countdown timer is expired |

### Values

| key | Type | Description |
| --- | --- | ---- |
| seconds | number | seconds value |
| minutes | number | minutes value |
| hours | number | hours value |
| days | number | days value |
| pause | function | function to be called to pause timer |
| start | function | function if called after pause the timer will continue based on original expiryTimestamp |
| resume | function | function if called after pause the timer will continue countdown from last paused state |


---

## Values
## `useStopwatch`

### Example

```javascript
import React from 'react';
import { useStopwatch } from 'react-timer-hook';

function MyStopwatch() {
const {
seconds,
minutes,
hours,
days,
start,
pause,
reset,
} = useStopwatch({ autoStart: true });


return (
<div style={{textAlign: 'center'}}>
<h1>react-timer-hook</h1>
<p>Stopwatch Demo</p>
<div style={{fontSize: '100px'}}>
<span>{days}</span>:<span>{hours}</span>:<span>{minutes}</span>:<span>{seconds}</span>
</div>
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
<button onClick={reset}>Reset</button>
</div>
);
}

export default function App() {
return (
<div>
<MyStopwatch />
</div>
);
}
```

### Settings

| key | Type | Required | Description |
| --- | --- | --- | ---- |
| autoStart | boolean | No | if set to `true` stopwatch will auto start |

### Values

| key | Type | Description |
| --- | --- | ---- |
| seconds | number | seconds value |
| minutes | number | minutes value |
| hours | number | hours value |
| days | number | days value |
| startTimer | function | function to be called to start timer |
| stopTimer | function | function to be called to stop timer |
| resetTimer | function | function to be called to reset timer to 0:0:0:0 |
| start | function | function to be called to start stopwatch |
| pause | function | function to be called to pause stopwatch |
| reset | function | function to be called to reset stopwatch to 0:0:0:0 |


---

### Deprecation Warning:

Starting from `v1.1.0` and above default export `useTimer` is deprecated, your old code will still work but it is better to start using named exports `{ useTimer, useStopwatch }`
31 changes: 21 additions & 10 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,38 @@
import React from 'react';
import useTimer from './useTimer';
import { useTimer } from './useTimer';

export default function App() {
function MyTimer({ expiryTimestamp }) {
const {
seconds,
minutes,
hours,
days,
startTimer,
stopTimer,
resetTimer,
} = useTimer({ autoStart: true });
start,
pause,
resume
} = useTimer({ expiryTimestamp, onExpire: () => console.warn('onExpire called') });


return (
<div style={{textAlign: 'center'}}>
<h1>react-timer-hook Demo</h1>
<h1>react-timer-hook </h1>
<p>Timer Demo</p>
<div style={{fontSize: '100px'}}>
<span>{days}</span>:<span>{hours}</span>:<span>{minutes}</span>:<span>{seconds}</span>
</div>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
<button onClick={resetTimer}>Reset</button>
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
<button onClick={resume}>Resume</button>
</div>
);
}

export default function App() {
var t = new Date();
t.setSeconds(t.getSeconds() + 600); // 10 minutes timer
return (
<div>
<MyTimer expiryTimestamp={t} />
</div>
);
}
103 changes: 76 additions & 27 deletions src/useTimer.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
import { useState, useEffect, useRef } from 'react';

export default function useTimer(settings) {
const { autoStart, expiryTimestamp, onExpire } = settings || {};
export default function deprecatedUseTimer(settings) {
// didMount effect
useEffect(() => {
console.warn('react-timer-hook: default export useTimer is deprecated, use named exports { useTimer, useStopwatch } instead');
},[]);

if(settings.expiryTimestamp) {
return useTimer(settings);
} else {
return useStopwatch(settings);
}
}

/* --------------------- useStopwatch ----------------------- */

export function useStopwatch(settings) {
const { autoStart } = settings || {};

// Seconds
const [seconds, setSeconds] = useState(0);
Expand Down Expand Up @@ -49,39 +64,69 @@ export default function useTimer(settings) {

// Control functions
const intervalRef = useRef();
function start(isFunctionTrigger) {
if (expiryTimestamp) {
isValidExpiryTimestamp(expiryTimestamp) && runCountdownTimer();
} else if(autoStart) {
runTimer();
}
}

function runCountdownTimer() {
function start() {
if(!intervalRef.current) {
calculateExpiryDate();
intervalRef.current = setInterval(() => calculateExpiryDate(), 1000);
intervalRef.current = setInterval(() => addSecond(), 1000);
}
}

function startTimer() {
runTimer();
function pause() {
if(intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = undefined;
}
}

function stopTimer() {
if(intervalRef.current) {
function reset() {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = undefined;
}
setSeconds(0);
setMinutes(0);
setHours(0);
setDays(0);
}

function runTimer() {
if(!intervalRef.current) {
intervalRef.current = setInterval(() => addSecond(), 1000);
// didMount effect
useEffect(() => {
if(autoStart) {
start();
}
return reset;
},[]);

return { seconds, minutes, hours, days, start, pause, reset };
}

/* ---------------------- useTimer --------------------- */

export function useTimer(settings) {
const { expiryTimestamp, onExpire } = settings || {};

const [seconds, setSeconds] = useState(0);
const [minutes, setMinutes] = useState(0);
const [hours, setHours] = useState(0);
const [days, setDays] = useState(0);

const intervalRef = useRef();

function start() {
if(isValidExpiryTimestamp(expiryTimestamp) && !intervalRef.current) {
calculateExpiryDate();
intervalRef.current = setInterval(() => calculateExpiryDate(), 1000);
}
}

function pause() {
if(intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = undefined;
}
}

function resetTimer() {
function reset() {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = undefined;
Expand All @@ -92,6 +137,10 @@ export default function useTimer(settings) {
setDays(0);
}

function resume() {
// TODO implement countdown timer resume after pause
}

// Timer expiry date calculation
function calculateExpiryDate() {
var now = new Date().getTime();
Expand All @@ -101,7 +150,7 @@ export default function useTimer(settings) {
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if(seconds < 0) {
resetTimer();
reset();
isValidOnExpire(onExpire) && onExpire();
} else {
setSeconds(seconds);
Expand All @@ -114,15 +163,15 @@ export default function useTimer(settings) {
// didMount effect
useEffect(() => {
start();
return stopTimer;
return reset;
},[]);


// Validate expiryTimestamp
function isValidExpiryTimestamp(expiryTimestamp) {
const isValid = expiryTimestamp && (new Date(expiryTimestamp)).getTime() > 0;
if(expiryTimestamp && !isValid) {
console.warn('react-timer-hook: Invalid expiryTimestamp settings passed', expiryTimestamp);
const isValid = (new Date(expiryTimestamp)).getTime() > 0;
if(!isValid) {
console.warn('react-timer-hook: { useTimer } Invalid expiryTimestamp settings', expiryTimestamp);
}
return isValid;
}
Expand All @@ -131,10 +180,10 @@ export default function useTimer(settings) {
function isValidOnExpire(onExpire) {
const isValid = onExpire && typeof onExpire === 'function';
if(onExpire && !isValid) {
console.warn('react-timer-hook: Invalid onExpire settings function passed', onExpire);
console.warn('react-timer-hook: { useTimer } Invalid onExpire settings function', onExpire);
}
return isValid;
}

return { seconds, minutes, hours, days, startTimer, stopTimer, resetTimer };
return { seconds, minutes, hours, days, start, pause, resume };
}