javascriptreactjssetintervalclearintervalmousedown

clearInterval not clearing the set interval onMouseUp


Trying to make a button event onMouseDown, a function should run at the end of the set amount of time. The function runs onMouseDown and clears the interval onMouseUp, but the interval still runs after releasing the button.

This is the code currently. I have the interval global and set it in the planting function. It should unset in the notPlanting function, but it does not.

import React from "react";

function PlantDefuser() {
    var interval

    function planting() {
        interval = setInterval(() => {
            console.log("Defuser Planted")
        }, 1000)
    }

    function notPlanting() {
        console.log(interval)
        clearInterval(interval)
    }

    return (
        <button onMouseDown={planting} onMouseUp={notPlanting}>Press and Hold</button>
    )
}

export default PlantDefuser

Solution

  • This could help you:

    useRef allows us to store and update data in the component without triggering a re-render. Now the only re-render happens when the props are updated.

    We can store interval in a ref like so

    import { useRef } from "react";
    
    const PlantDefuser = () => {
      const interval = useRef();
    
      function planting() {
        interval.current = setInterval(() => {
          console.log("Defuser Planted");
        }, 1000);
      }
    
      function notPlanting() {
        clearInterval(interval.current);
      }
    
      return (
        <button onMouseDown={planting} onMouseUp={notPlanting}>
          Press and Hold
        </button>
      );
    }
    
    export default PlantDefuser