Skip to content

Commit 02b5de1

Browse files
committed
add isRunning state to useTimer
1 parent b739db7 commit 02b5de1

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

app/App.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ function MyTimer({ expiryTimestamp }) {
1212
pause,
1313
resume,
1414
restart,
15+
isRunning,
1516
} = useTimer({ expiryTimestamp, onExpire: () => console.warn('onExpire called') });
1617

1718

@@ -36,6 +37,7 @@ function MyTimer({ expiryTimestamp }) {
3637
>
3738
Restart
3839
</button>
40+
<p>{isRunning ? 'running' : 'not running'}</p>
3941
</div>
4042
);
4143
}

src/useTimer.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ export default function useTimer(settings) {
55
const { expiryTimestamp: expiry, onExpire } = settings || {};
66
const [expiryTimestamp, setExpiryTimestamp] = useState(expiry);
77
const [seconds, setSeconds] = useState(Time.getSecondsFromExpiry(expiryTimestamp));
8+
const [isRunning, setIsRunning] = useState(true);
89
const intervalRef = useRef();
910

1011
function clearIntervalRef() {
@@ -16,11 +17,13 @@ export default function useTimer(settings) {
1617

1718
function handleExpire() {
1819
clearIntervalRef();
20+
setIsRunning(false);
1921
Validate.onExpire(onExpire) && onExpire();
2022
}
2123

2224
function start() {
2325
if (!intervalRef.current) {
26+
setIsRunning(true);
2427
intervalRef.current = setInterval(() => {
2528
const secondsValue = Time.getSecondsFromExpiry(expiryTimestamp);
2629
if (secondsValue <= 0) {
@@ -32,11 +35,13 @@ export default function useTimer(settings) {
3235
}
3336

3437
function pause() {
38+
setIsRunning(false);
3539
clearIntervalRef();
3640
}
3741

3842
function resume() {
3943
if (!intervalRef.current) {
44+
setIsRunning(true);
4045
intervalRef.current = setInterval(() => setSeconds((prevSeconds) => {
4146
const secondsValue = prevSeconds - 1;
4247
if (secondsValue <= 0) {
@@ -62,6 +67,6 @@ export default function useTimer(settings) {
6267

6368

6469
return {
65-
...Time.getTimeFromSeconds(seconds), start, pause, resume, restart,
70+
...Time.getTimeFromSeconds(seconds), start, pause, resume, restart, isRunning,
6671
};
6772
}

0 commit comments

Comments
 (0)