Skip to content

Instantly share code, notes, and snippets.

@nifrasismail
Created May 27, 2024 12:41
Show Gist options
  • Save nifrasismail/414efa420536e8a7dbc443267808fa12 to your computer and use it in GitHub Desktop.
Save nifrasismail/414efa420536e8a7dbc443267808fa12 to your computer and use it in GitHub Desktop.
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