Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
Canceling a timeout in useEffect() if user scrolls with react hooks

Basically the same question as How to cancel a javascript function if the user scrolls the page but using react hooks.

I wrote react code that scrolls down to the end of the page after 3 seconds.


const scrollToEnd = () => { /* implementation omitted */ }

useEffect(() => {
    const id = setTimeout(() => scrollToEnd(), 3000)
    return () => clearTimeout(id)
}, [])

I want modify this code so that if the user manually scrolls the page before this timeout, the timeout is cleared.

I was thinking of a solution like:

const [hasScrolled, setHasScrolled] = useState(false);
const scrollToEnd = () => { /* implementation omitted */ }

useEffect(() => {
    const setHasScrolledCallback = () => setHasScrolled(true)
    window.addEventListener("scroll", setHasScrolledCallback);
    return () => window.removeEventListener("scroll", setHasScrolledCallback);
}, []);

useEffect(() => {
    const scrollCallback = () => { if (hasScrolled) scrollToEnd() }
    const id = setTimeout(scrollCallback, 3000)
    return () => clearTimeout(id)
}, [])

This works, but I don't think this is the correct way to approach this problem, because the scroll event is fired multiple times, even after the timeout occurs. Also the scrollCallback isn't really canceled, it runs anyway even if it does nothing.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!