Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React notify after a certain time when button is not clicked

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading