Skip to content

Commit a6986b2

Browse files
committed
handle pause and start similar to current behaviour
1 parent 24df843 commit a6986b2

File tree

2 files changed

+13
-12
lines changed

2 files changed

+13
-12
lines changed

.eslintrc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"react-hooks/rules-of-hooks": "error",
88
"react-hooks/exhaustive-deps": "warn",
99
"react/jsx-filename-extension": 0,
10+
"import/prefer-default-export": 0,
1011
"no-unused-expressions": [ 2,{
1112
"allowShortCircuit": true,
1213
}],

src/useTimer.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import { useState, useEffect } from 'react';
1+
import { useState } from 'react';
22
import { Time, Validate } from './utils';
33
import { useInterval } from './hooks';
44

55
export default function useTimer({ expiryTimestamp: expiry, onExpire, autoStart }) {
66
const [expiryTimestamp, setExpiryTimestamp] = useState(expiry);
77
const [seconds, setSeconds] = useState(Time.getSecondsFromExpiry(expiryTimestamp));
8-
const [isRunning, setIsRunning] = useState(false);
8+
const [isRunning, setIsRunning] = useState(autoStart);
9+
const [didStart, setDidStart] = useState(autoStart);
910

1011
function handleExpire() {
1112
Validate.onExpire(onExpire) && onExpire();
@@ -15,17 +16,22 @@ export default function useTimer({ expiryTimestamp: expiry, onExpire, autoStart
1516
setIsRunning(false);
1617
}
1718

18-
function start() {
19-
setIsRunning(true);
20-
}
21-
2219
function resume() {
2320
const time = new Date();
2421
time.setSeconds(time.getSeconds() + seconds); // calculate new expiry timestamp based on last paused seconds count
2522
setExpiryTimestamp(time);
2623
setIsRunning(true);
2724
}
2825

26+
function start() {
27+
if (didStart) {
28+
setIsRunning(true);
29+
} else {
30+
resume();
31+
setDidStart(true);
32+
}
33+
}
34+
2935
function restart(newExpiryTimestamp) {
3036
setExpiryTimestamp(newExpiryTimestamp);
3137
setSeconds(Time.getSecondsFromExpiry(newExpiryTimestamp));
@@ -39,12 +45,6 @@ export default function useTimer({ expiryTimestamp: expiry, onExpire, autoStart
3945
setSeconds(secondsValue);
4046
} : () => {}, 1000);
4147

42-
useEffect(() => {
43-
if (autoStart) {
44-
setIsRunning(true);
45-
}
46-
}, [autoStart]);
47-
4848
return {
4949
...Time.getTimeFromSeconds(seconds), start, pause, resume, restart, isRunning,
5050
};

0 commit comments

Comments
 (0)