【问题标题】:clearTimeout prevents setTimeout from runningclearTimeout 阻止 setTimeout 运行
【发布时间】:2021-12-10 12:13:42
【问题描述】:
  const func = () => {
    const id = setTimeout(() => {
      //do something with an element
    }, 300);
    return id;
  };

  useEffect(() => {
    const id = func();
    return () => clearTimeout(id);
  }, [click]);

当我点击太快时,这是useEffect的触发器,它可能导致传递给setTimeout的函数无法运行。

有什么问题?

以下替代解决方案是否一样好?

  const func = () => {
    const id = setTimeout(() => {
      if (element is stilled defined) {
      // do something  
      }
    }, 300);
    return id;
  };

  useEffect(() => {
    func();
  }, [click]);

【问题讨论】:

  • 你在做一种简单的油门功能吗?
  • 不知道你说的油门是什么意思。
  • Throttle/Debounce,限制函数调用频率的方法。这是你想要做的吗?如果 func 在 300 毫秒内再次被调用,它将清除之前的超时并开始一个新的。
  • 啊,你的意思是在javascript程序中的特定时间范围内只能存在一个clearTimeout实例吗?
  • 什么是click?在这种情况下,您似乎需要检查是否单击!== null。

标签: javascript html settimeout


【解决方案1】:

如果我正确理解了您的代码,您似乎希望将回调函数延迟一些增量。我建议使用 React ref 来跟踪一组正在运行的计时器。调用该函数时,将新的超时 id 添加到此数组中,当超时到期时将其从数组中清除。使用 onUnmount useEffect 清除任何运行超时。

const timeoutRef = useRef([]);

const func = () => {
  const id = setTimeout(() => {
    //do something with an element
    dequeueCallback(id);
  }, 3000);
  enqueueCallback(id);
};

const enqueueCallback = (id) => {
  timeoutRef.current.push(id);
};
const dequeueCallback = (id) => {
  timeoutRef.current = timeoutRef.current.filter((el) => el !== id);
};

useEffect(() => {
  // clear any running timeouts upon unmount
  return () => {
    timeoutRef.current.forEach(clearTimeout);
  };
}, []);

演示

【讨论】:

    【解决方案2】:

    你可以通过清理函数来解决这个问题,清理函数会在效果重新渲染触发时触发,所以你可以把必须发生的事情放在任何动作之前,这样,解决方案就是这样:

      useEffect(() => {
        console.log(myEvent);
        // You can add condtion here and above of cleaner
        const timer = setTimeout(() => {
          if(myEvent !== null){// Internal contion
            alert("HI MAN");
          }
        }, 2000);
    
        return () => clearTimeout(timer);// This is important part
      }, [myEvent]);
    

    检查这个例子:

    import { useEffect, useState } from "react";
    import "./styles.css";
    
    export default function App() {
      const [myEvent, setMyEvent] = useState(null);
    
      useEffect(() => {
        console.log(myEvent);
        
        const timer = setTimeout(() => {
          if(myEvent !== null){
            alert("HI MAN");
          }
        }, 2000);
    
        return () => clearTimeout(timer);
      }, [myEvent]);
    
      return (
        <div className="App">
          <button onClick={() => {
            setMyEvent(Math.random);
          }}>test</button>
        </div>
      );
    }
    

    这是URL Demo。

    反应参考: React Hooks

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-23
      • 2018-06-21
      • 1970-01-01
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      相关资源
      最近更新 更多