-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
41 lines (34 loc) · 902 Bytes
/
index.js
File metadata and controls
41 lines (34 loc) · 902 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'use strict';
const { useEffect, useState } = require('react');
function useCountdownSeconds (durationSec, warningSec) {
const [startTime, start] = useState(0);
const [timeLeft, setTimeLeft] = useState(0);
const [isWarning, warn] = useState(false);
const [intervalId, setIntervalId] = useState(null);
useEffect(() => {
// incoming expiration or warning
if (intervalId) {
clearInterval(intervalId);
warn(false);
}
// expired
if (!startTime) {
return;
}
// start timer
let t = durationSec;
setTimeLeft(t--);
setIntervalId(setInterval(() => {
setTimeLeft(t);
if (!t) {
start(0);
} else if (t === warningSec) {
warn(true);
}
// decrement every second
t--;
}, 1000))
}, [startTime])
return { start, startTime, timeLeft, isWarning }
}
module.exports = useCountdownSeconds;