Created
May 27, 2024 12:41
-
-
Save nifrasismail/414efa420536e8a7dbc443267808fa12 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 } from "react" | |
let intervalId; | |
function StopWatch() { | |
const [counter, setCounter] = useState(0) | |
const handleClick = (action) => { | |
switch(action){ | |
case 'start' : { | |
intervalId = setInterval(() => { | |
setCounter((prev) => prev + 1) | |
},1000) | |
break; | |
} | |
case 'pause' : { | |
clearInterval(intervalId); | |
intervalId = null; | |
break; | |
} | |
case 'reset' : { | |
clearInterval(intervalId); | |
intervalId = null | |
setCounter(0) | |
break; | |
} | |
default : { | |
} | |
} | |
} | |
return ( | |
<div> | |
<h1>{counter}</h1> | |
<button onClick={() => handleClick('start')}>Start</button> | |
<button onClick={() => handleClick('pause')}>Pause</button> | |
<button onClick={() => handleClick('reset')}>Reset</button> | |
</div> | |
) | |
} | |
export default StopWatch | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment