javascript - 反应:onKeyDown 事件的去抖动
问题描述
我在我的 React 类组件中有输入:
changeVal(event) {
console.log(event.keyKode)
}
...
return(
<input onKeyDown={event => this.changeVal(event)} />
)
如何在没有 lodash 的情况下以 500 毫秒的去抖动在 keyDown 上调用函数?
我尝试了下一件事:
debounce = (callback, delay) => {
const timerClear = () => clear = true;
var clear = true;
return event => {
if (clear) {
clear = false;
setTimeout(timerClear, delay);
callback(event);
}
}
}
return(
<input onKeyDown={event => this.debounce(this.changeVal, 500)} />
)
但这根本不起作用。
解决方案
尝试
const debounce = (func, wait = 500) => {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
};
}
推荐阅读
- javascript - 如果失败,Puppeteer 如何延迟重试 url 获取
- node.js - 从 nodejs 选择器服务器中的应用程序收到的不完整响应
- c# - C# - 有没有办法从具有动态类型的泛型类继承
- c++ - 如何修复“1/0!+ 1/1!+ 1/2!+....+ 1/n!”的代码
- java - 当构造函数只被调用一次时,一个 volatile 字段如何对每个线程都是唯一的?
- google-cloud-platform - GCP 市场 - 服务提供商订阅权限
- c - 如何将 AddressSanitizer 与动态链接的 Pthreads 库结合使用?
- sql - SQL - 根据 2 个字段查找计数
- javascript - 提交之前是否应该通过 javascript 验证表单?
- mongodb - 在查询特定 ID 时,我在 graphql 中遇到错误