I want to make a Reverse Countdown Timer in which that has an input field and when I type a number and press the "Enter" key, the countdown starts. but the problem is when I want to stop the previous interval and starts new interval with new number and press Enter key, it runs parallel with previous one.
I'm pretty new to react, can somebody give me some advice to fix the problem ?
import React, {useState} from "react";
const App = () => {
const [ctime, setctime]=useState();
const enterdown=(value)=>{
clearInterval(interval);
setctime(value);
var interval = setInterval(()=>{
value--;
if(value==0){
clearInterval(interval);
}
setctime(value);
},1000)
}
return (
<div className="wrapper">
<div id="whole-center">
<h1>
Reverse countdown for<input id="timeCount" onKeyDown={(e)=>{e.key == "Enter" ?(enterdown(e.target.value)) :null}} /> sec.
</h1>
</div>
<div id="current-time">{ctime}</div>
</div>
)
}
export default App;
CodePudding user response:
use this const interval = useRef();
instead of var interval
Full working code: Also codesandbox link: https://codesandbox.io/s/zealous-monad-thhrvz?file=/src/App.js
const App = () => {
const interval = useRef();
const [ctime, setctime] = useState();
const enterdown = (value) => {
clearInterval(interval.current);
setctime(value);
interval.current = setInterval(() => {
value--;
if (value == 0) {
clearInterval(interval.current);
}
setctime(value);
}, 1000);
};
return (
<div className="wrapper">
<div id="whole-center">
<h1>
Reverse countdown for
<input
id="timeCount"
onKeyDown={(e) => {
e.key == "Enter" ? enterdown(e.target.value) : null;
}}
/>{" "}
sec.
</h1>
</div>
<div id="current-time">{ctime}</div>
</div>
);
};
CodePudding user response:
The interval
variable gets created each time the App
function is run.
Which is in this case each time you press Enter.
It can be fixed by placing it out of the App function.
let interval;
const App = () => {
const [ctime, setctime] = useState();
const enterdown = (value) => {
clearInterval(interval);
setctime(value);
interval = setInterval(() => {
value--;
if (value === 0) {
clearInterval(interval);
}
setctime(value);
}, 1000);
};
// ...
Another solution would be using useRef