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

144
Views
How to pass React state variable into setInterval function

I created a drag and drop menu and so far everything works, however, I have run into a small coding problem for my last step. I need to get the menu of items to automatically scroll when the dragged item is towards the bottom of the container (or top). I decided to structure it so that when the cursor dragging the item falls below a specific range towards the bottom, a scroll function will trigger and continually scroll down at a pace I can set. In order to achieve this I set up a setInterval function and will continually call a scrollBy function.

My issue is that In order to stop the setInterval and call clearInterval, I need to know when the position of the cursor is no longer in that range. Every time the function is called in setInterval, it takes a snapshot of the current state variables. Instead of updating the state of those variables (yAxis position) within the function, it is stuck on the first value it gets.

The yPoisiton is obtained with the window.event.clientY from another component.

    document.onmousemove = (e) => {
      if (dragging.state) {
        var newYPos = window.event.clientY;
        setYPos(newYPos);
        handleScroll(newYPos, dragging.state);

The rest of the code goes as follows:

  const menuContainer = useRef();
  const [scrolling, setScrolling] = useState(false);
  const [yPos, setYPos] = useState(null);
  const [dragging, setDragging] = useState({
    state: false,
    index: null,
    y: null,
    height: null,
  });

  function continueScrolling() {
    console.log("continueScrolling function");
    console.log(yPos); // Same value even after updating via setYPos) 
    const date = new Date(); 
    console.log(date.toLocaleTimeString()); //Different values in accordance to the time
  }

  console.log("Index.js yPos");
  console.log(yPos); // Different values every render when dragging
  const handleScroll = (draggingYPos, isDragging) => { // This is triggered onMouseMove in another component
    if (
      draggingYPos >
        menuContainer.current.getBoundingClientRect().bottom - 100 &&
      isDragging
    ) {
      setScrolling(true); // On the first cycle scrolling == false and executes the setInterval function. Each subsequent call is then skipped. 
      if (scrolling) {
        return;
      } else {
        var intr = setInterval(function () {
          continueScrolling(); // Different method of testing and trying to get the current yPos in the function

//Commented but shows a bit of what I'm trying to accomplish
          // if (
          //   !(
          //     yPos >
          //       menuContainer.current.getBoundingClientRect().bottom - 100 &&
          //     dragging.state
          //   )
          // )
          //   clearInterval(intr);
        }, 1000);

Please let me know if there is more information you need or anything else I can clarify.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is a temporary solution I found to my problem, however, I would still like to know a more proper and robust solution if anyone has one, as well as information as to the scope of functions, React state, and how to pass them between one another.

I realize that it is not recommended to mutate states directly, however, this is my only current working solution. If I create a temporary value and pass in the setInterval, it will call setInterval a second time and will still be active after clearing it.

If I declare a global const variable, I cannot reassign the variable with setInterval. When I declared a global variable with var, the setInterval function continued even after I cleared it.

Adjusted code:

const [scroll, setScroll] = useState(null);

const handleScroll = (draggingYPos, isDragging) => {
    if (
      draggingYPos >
        menuContainer.current.getBoundingClientRect().bottom - 100 &&
      isDragging
    ) {
      setScrolling(true);
      if (scrolling) {
        return;
      } else {
        var count = 0;
        if (
          !(
            yPos > menuContainer.current.getBoundingClientRect().bottom - 100 &&
            dragging.state
          )
        ) {
          setScroll(
            setInterval(function () {
              count += 1;
              console.log(count);
            }, 1000)
          );
        }
      }
    } else {
      console.log("Not Scrolling");
      setScroll(clearInterval(scroll));
      setScrolling(false);
    }
  };



about 4 years ago · Juan Pablo Isaza Report
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!