0

Want to write a function that triggers if user is scolling, but it seems that setTimeout isnt being triggered in this case. It should set the state to false when user is not scrolling.

  const handleScollTab = useCallback(
    () => {
      console.log('trriiii');
      dispatch(getScrollYTrigger(true));

      let timer = setTimeout(() => {
        dispatch(getScrollYTrigger(false));
      }, 1000);
      clearTimeout(timer);
    },
    [dispatch]
  );

  useEffect(() => {
    window.addEventListener("scroll", handleScollTab);

    return () => {
      window.removeEventListener("scroll", handleScollTab);
    };
  }, [handleScollTab]);

2 Answers2

1

https://codesandbox.io/s/divine-feather-xmdzm?file=/src/App.js

You can do like this:

import "./styles.css";
import React from "react";

export default function App() {
  const [trigger, setTrigger] = React.useState(false);
  const setTimerRef = React.useRef();
  const handleScollTab = React.useCallback(() => {
    console.log("trriiii");
    setTrigger(true);
    console.log("set true");
    if (setTimerRef.current) {
      clearTimeout(setTimerRef.current);
      setTimerRef.current = null;
    }

    setTimerRef.current = setTimeout(() => {
      console.log("set false");
      setTrigger(false);
      clearTimeout(setTimerRef.current);
      setTimerRef.current = null;
    }, 1000);
  }, [setTimerRef]);

  React.useEffect(() => {
    window.addEventListener("scroll", handleScollTab);

    return () => {
      window.removeEventListener("scroll", handleScollTab);
    };
  }, [handleScollTab]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

By doing this you can effectively clearTimeout that created by previous handler calls. And clear last one as well.

Zhang TianYu
  • 1,163
  • 5
  • 11
  • There should be a `clearTimeout` inside the `useEffect` cleanup function IMO (and resetting the ref too). Also, I don't see the need of clearing the timeout inside the `setTimeout` itself – Luís Alves Mar 24 '23 at 11:22
0

you clearTimeout instant after setTimout() before await 1000

for fix remove clearTimeout()

HardCoreQual
  • 331
  • 1
  • 3
  • 11