Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ function MyTimer({ expiryTimestamp }) {
days,
start,
pause,
resume
resume,
restart
} = useTimer({ expiryTimestamp, onExpire: () => console.warn('onExpire called') });


Expand All @@ -23,6 +24,12 @@ function MyTimer({ expiryTimestamp }) {
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
<button onClick={resume}>Resume</button>
<button onClick={() => {
// Resets to 10 minutes timer
var t = new Date();
t.setSeconds(t.getSeconds() + 600);
restart(t)
}}>restart</button>
</div>
);
}
Expand Down
15 changes: 11 additions & 4 deletions src/useTimer.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ export function useStopwatch(settings) {
/* ---------------------- useTimer --------------------- */

export function useTimer(settings) {
const { expiryTimestamp, onExpire } = settings || {};
const { expiryTimestamp: expiry, onExpire } = settings || {};
const [expiryTimestamp, setExpiryTimestamp] = useState(expiry);

const [seconds, setSeconds] = useState(0);
function subtractSecond() {
Expand Down Expand Up @@ -164,7 +165,7 @@ export function useTimer(settings) {
function start() {
if(isValidExpiryTimestamp(expiryTimestamp) && !intervalRef.current) {
calculateExpiryDate();
intervalRef.current = setInterval(() => calculateExpiryDate(), 1000);
intervalRef.current = setInterval(() => subtractSecond(), 1000);
}
}

Expand Down Expand Up @@ -192,6 +193,12 @@ export function useTimer(settings) {
}
}

function restart(newExpiryTimestamp) {
reset();
setExpiryTimestamp(newExpiryTimestamp);
}


// Timer expiry date calculation
function calculateExpiryDate() {
var now = new Date().getTime();
Expand All @@ -215,7 +222,7 @@ export function useTimer(settings) {
useEffect(() => {
start();
return reset;
},[]);
},[expiryTimestamp]);


// Validate expiryTimestamp
Expand All @@ -236,7 +243,7 @@ export function useTimer(settings) {
return isValid;
}

return { seconds, minutes, hours, days, start, pause, resume };
return { seconds, minutes, hours, days, start, pause, resume, restart };
}


Expand Down