Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda