Skip to content

Commit e41bdbc

Browse files
committed
Created Reset Functionality for useTimer.
1 parent 95e4d58 commit e41bdbc

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/App.js

Lines changed: 3 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,7 @@ function MyTimer({ expiryTimestamp }) {
2324
<button onClick={start}>Start</button>
2425
<button onClick={pause}>Pause</button>
2526
<button onClick={resume}>Resume</button>
27+
<button onClick={() => restart(500) /* resets to 50 seconds */}>restart</button>
2628
</div>
2729
);
2830
}

src/useTimer.js

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

107107
export function useTimer(settings) {
108-
const { expiryTimestamp, onExpire } = settings || {};
108+
let { expiryTimestamp, onExpire } = settings || {};
109109

110110
const [seconds, setSeconds] = useState(0);
111111
function subtractSecond() {
@@ -164,7 +164,7 @@ export function useTimer(settings) {
164164
function start() {
165165
if(isValidExpiryTimestamp(expiryTimestamp) && !intervalRef.current) {
166166
calculateExpiryDate();
167-
intervalRef.current = setInterval(() => calculateExpiryDate(), 1000);
167+
intervalRef.current = setInterval(() => subtractSecond(), 1000);
168168
}
169169
}
170170

@@ -192,6 +192,19 @@ export function useTimer(settings) {
192192
}
193193
}
194194

195+
function restart(offset) {
196+
reset();
197+
// Calculate fresh expiry and start timer again with new expiry ammount
198+
calcNewExpiry(offset);
199+
start();
200+
}
201+
202+
function calcNewExpiry(offset) {
203+
let t = new Date();
204+
t.setSeconds(t.getSeconds() + offset);
205+
expiryTimestamp = t;
206+
}
207+
195208
// Timer expiry date calculation
196209
function calculateExpiryDate() {
197210
var now = new Date().getTime();
@@ -236,7 +249,7 @@ export function useTimer(settings) {
236249
return isValid;
237250
}
238251

239-
return { seconds, minutes, hours, days, start, pause, resume };
252+
return { seconds, minutes, hours, days, start, pause, resume, restart };
240253
}
241254

242255

0 commit comments

Comments
 (0)