I want to print an alert to the console if it doesn’t click a button within a certain period of time, but if it clicks it doesn’t show this alert
I tried using settimeout like this but it gives a warning after clicking
It’s actually a very simple method that I tried.
const [clicked , setClicked] = useState(false);
useEffect(() => {
setTimeout(()=>{
if (!clicked) {
console.log(`alert`);
}
},[3000])
}, [])
return <button onClick={()=>setClicked(true)} className="ErrorEntrySideBttn">try me</button>
>Solution :
As-is, you should have clicked in your effect hook and then you can cancel the timeout in the effect hook’s cleanup function:
const [clicked , setClicked] = useState(false);
useEffect(() => {
let timeout;
if (!clicked) {
timeout = setTimeout(() => {
console.log(`alert`);
}, 3000)
}
return () => {
clearTimeout(timeout);
}
}, [clicked]);
return <button onClick={()=>setClicked(true)} className="ErrorEntrySideBttn">try me</button>
Another approach would be to use a ref to track a boolean assuming you never want to have anything else dependent on this ref:
const clicked = useRef(false);
useEffect(() => {
const timeout = setTimeout(() => {
if (!clicked.current) {
console.log(`alert`);
}
}, 3000)
return () => {
clearTimeout(timeout)
}
}, []);
return <button onClick={() => { clicked.current = true }} className="ErrorEntrySideBttn">try me</button>