Build a Stopwatch component with Start, Stop, and Reset functionality.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
import React, { useState, useRef } from 'react';
function Stopwatch() {
const [time, setTime] = useState(0);
const [isRunning, setIsRunning] = useState(false);
const intervalRef = useRef(null);
const start = () => {
if (!isRunning) {
setIsRunning(true);
intervalRef.current = setInterval(() => {
setTime((prevTime) => prevTime + 10);
}, 10);
}
};
const stop = () => {
if (isRunning) {
clearInterval(intervalRef.current);
setIsRunning(false);
}
};
const reset = () => {
clearInterval(intervalRef.current);
setIsRunning(false);
setTime(0);
};
const formatTime = (time) => {
const getMilliseconds = `0${(time % 1000) / 10}`.slice(-2);
const getSeconds = `0${Math.floor((time / 1000) % 60)}`.slice(-2);
const getMinutes = `0${Math.floor((time / 60000) % 60)}`.slice(-2);
return `${getMinutes}:${getSeconds}:${getMilliseconds}`;
};
return (
<div>
<h1>{formatTime(time)}</h1>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
<button onClick={reset}>Reset</button>
</div>
);
}
export default Stopwatch;