【发布时间】: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