Skip to content

Commit 06e62fc

Browse files
authored
Merge pull request #5 from IzzleNizzle/master
Created Reset Functionality for useTimer.
2 parents 95e4d58 + 91e8b7d commit 06e62fc

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

src/App.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ function MyTimer({ expiryTimestamp }) {
99
days,
1010
start,
1111
pause,
12-
resume
12+
resume,
13+
restart
1314
} = useTimer({ expiryTimestamp, onExpire: () => console.warn('onExpire called') });
1415

1516

@@ -23,6 +24,12 @@ function MyTimer({ expiryTimestamp }) {
2324
<button onClick={start}>Start</button>
2425
<button onClick={pause}>Pause</button>
2526
<button onClick={resume}>Resume</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>
2633
</div>
2734
);
2835
}

src/useTimer.js

Lines changed: 11 additions & 4 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-
const { 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() {
@@ -164,7 +165,7 @@ export function useTimer(settings) {
164165
function start() {
165166
if(isValidExpiryTimestamp(expiryTimestamp) && !intervalRef.current) {
166167
calculateExpiryDate();
167-
intervalRef.current = setInterval(() => calculateExpiryDate(), 1000);
168+
intervalRef.current = setInterval(() => subtractSecond(), 1000);
168169
}
169170
}
170171

@@ -192,6 +193,12 @@ export function useTimer(settings) {
192193
}
193194
}
194195

196+
function restart(newExpiryTimestamp) {
197+
reset();
198+
setExpiryTimestamp(newExpiryTimestamp);
199+
}
200+
201+
195202
// Timer expiry date calculation
196203
function calculateExpiryDate() {
197204
var now = new Date().getTime();
@@ -215,7 +222,7 @@ export function useTimer(settings) {
215222
useEffect(() => {
216223
start();
217224
return reset;
218-
},[]);
225+
},[expiryTimestamp]);
219226

220227

221228
// Validate expiryTimestamp
@@ -236,7 +243,7 @@ export function useTimer(settings) {
236243
return isValid;
237244
}
238245

239-
return { seconds, minutes, hours, days, start, pause, resume };
246+
return { seconds, minutes, hours, days, start, pause, resume, restart };
240247
}
241248

242249

0 commit comments

Comments
 (0)