Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda