Last active
September 17, 2023 02:39
-
-
Save sharmaabhinav/539f894b6a08c0a440df79828c159a45 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useRef, useEffect } from 'react'; | |
const formattedTime = (time) => { | |
const paddedMin = String(Math.floor(time / 60)).padStart(2, '0'); | |
const paddedSec = String(time % 60).padStart(2, '0'); | |
return `${paddedMin}:${paddedSec}`; | |
}; | |
function Solution() { | |
const [time, setTime] = useState(0); | |
const [minute, setMinute] = useState(''); | |
const [second, setSecond] = useState(''); | |
const timerId = useRef(null); | |
const startTimer = () => { | |
timerId.current = setInterval(() => { | |
setTime((prevTime) => (prevTime === 0 ? prevTime : prevTime - 1)); | |
}, 1000); | |
}; | |
const clearTimer = () => { | |
clearInterval(timerId.current); | |
timerId.current = null; | |
}; | |
const onStart = () => { | |
const timeToSet = +(minute * 60 + second); | |
setTime(timeToSet); | |
clearTimer(); | |
if (timeToSet !== 0) { | |
startTimer(); | |
} | |
}; | |
const onPause = () => { | |
if (!timerId.current) { | |
time !== 0 && startTimer(); | |
} else { | |
clearTimer(); | |
} | |
}; | |
const onReset = () => { | |
clearTimer(); | |
setMinute(''); | |
setSecond(''); | |
setTime(0); | |
}; | |
useEffect(() => { | |
if (time === 0) { | |
clearTimer(); | |
} | |
}, [time]); | |
const onInputChange = (setter, value) => { | |
if (value === '') { | |
setter(''); | |
} else { | |
setter(Number(value)); | |
} | |
}; | |
return ( | |
<> | |
<label> | |
<input type="number" value={minute} onChange={(e) => onInputChange(setMinute, e.target.value)} /> | |
Minutes | |
</label> | |
<label> | |
<input type="number" value={second} onChange={(e) => onInputChange(setSecond, e.target.value)} /> | |
Seconds | |
</label> | |
<button onClick={onStart}>START</button> | |
<button onClick={onPause}>{timerId.current ? 'PAUSE' : 'RESUME'}</button> | |
<button onClick={onReset} disabled={!timerId.current && time === 0}> | |
RESET | |
</button> | |
<h1 data-testid="running-clock">{formattedTime(time)}</h1> | |
</> | |
); | |
} | |
export default Solution; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment