Skip to content

Commit 91e8b7d

Browse files
committed
Updates to implementation of Restart function
1 parent e41bdbc commit 91e8b7d

File tree

2 files changed

+11
-12
lines changed

2 files changed

+11
-12
lines changed

src/App.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,12 @@ function MyTimer({ expiryTimestamp }) {
2424
<button onClick={start}>Start</button>
2525
<button onClick={pause}>Pause</button>
2626
<button onClick={resume}>Resume</button>
27-
<button onClick={() => restart(500) /* resets to 50 seconds */}>restart</button>
27+
<button onClick={() => {
28+
// Resets to 10 minutes timer
29+
var t = new Date();
30+
t.setSeconds(t.getSeconds() + 600);
31+
restart(t)
32+
}}>restart</button>
2833
</div>
2934
);
3035
}

src/useTimer.js

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,8 @@ export function useStopwatch(settings) {
105105
/* ---------------------- useTimer --------------------- */
106106

107107
export function useTimer(settings) {
108-
let { expiryTimestamp, onExpire } = settings || {};
108+
const { expiryTimestamp: expiry, onExpire } = settings || {};
109+
const [expiryTimestamp, setExpiryTimestamp] = useState(expiry);
109110

110111
const [seconds, setSeconds] = useState(0);
111112
function subtractSecond() {
@@ -192,18 +193,11 @@ export function useTimer(settings) {
192193
}
193194
}
194195

195-
function restart(offset) {
196+
function restart(newExpiryTimestamp) {
196197
reset();
197-
// Calculate fresh expiry and start timer again with new expiry ammount
198-
calcNewExpiry(offset);
199-
start();
198+
setExpiryTimestamp(newExpiryTimestamp);
200199
}
201200

202-
function calcNewExpiry(offset) {
203-
let t = new Date();
204-
t.setSeconds(t.getSeconds() + offset);
205-
expiryTimestamp = t;
206-
}
207201

208202
// Timer expiry date calculation
209203
function calculateExpiryDate() {
@@ -228,7 +222,7 @@ export function useTimer(settings) {
228222
useEffect(() => {
229223
start();
230224
return reset;
231-
},[]);
225+
},[expiryTimestamp]);
232226

233227

234228
// Validate expiryTimestamp

0 commit comments

Comments
 (0)