【问题标题】:JS clear timer of previous function call before new function callJS在新函数调用之前清除上一个函数调用的计时器
【发布时间】:2021-01-17 20:11:54
【问题描述】:

我的 React 应用使用 Material UI 中的滑块组件。它的 onChange 事件调用一个函数来更新状态。我意识到我的组件会为每个滑块步骤重新渲染,这就是为什么我想在上次移动滑块后延迟状态更新 300 毫秒。

我的方法是通过 onChange 启动一个带有状态更新的计时器。当再次调用 onChange 时,应该取消之前的计时器。这是我仍在努力的部分。

setSliderValue 是一个接受数字来更新状态的函数。 如何仅在再次调用sliderChangeHandler时清除“计时器”?

const [sliderValue, setSliderValue] = useState(20);

const sliderChangeHandler = (event, newValue) => {
    const timer = setTimeout(setSliderValue, 300, newValue);
    clearTimeout(timer);
};

【问题讨论】:

    标签: javascript reactjs timer slider cleartimeout


    【解决方案1】:

    你应该在你的状态中设置setTimeout返回值:

    const [sliderValue, setSliderValue] = useState(20);
    const [timer, setTimer] = useState();
    
    const sliderChangeHandler = (event, newValue) => {
        clearTimeout(timer);
        const newTimer = setTimeout(setSliderValue, 300, newValue);
        setTimer(newTimer);
    };
    

    我建议你使用这个库来去抖动任何函数:https://github.com/xnimorz/use-debounce

    在你的情况下是:

    const [sliderValue, setSliderValue] = useState(20);
    
    const debounced = useDebouncedCallback(
      // function
      setSliderValue,
      // delay in ms
      300,
    );
    
    // some part of the code
    debounced.callback(30);
    

    在这种情况下,每次您拨打debounced.callback 都会取消之前的通话

    【讨论】:

    • 感谢您的提示!我更喜欢 vanilla JS/React 方式(你的第一个解决方案):)
    • 很好,很高兴它有帮助。干杯
    【解决方案2】:

    我使用useRef 钩子通常用于去抖动。比如:

    const timeoutRef = useRef(null)
    
    const [sliderValue, setSliderValue] = useState(20)
    
    const onChange = (e, v) => {
      clearTimeout(timeoutRef.current)
      timeoutRef.current = setTimeout(setSliderValue, 300, v)
    }
    
    

    节省一行代码;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 2014-12-31
      • 2022-01-12
      相关资源
      最近更新 更多