我如何需要:
- 第一个按键打开(搜索输入)启动搜索倒计时定时器并设置定时器为1秒。
- 每次下一个搜索键(搜索输入)重置搜索倒计时计时器为1秒。
- 当(搜索输入)不再更新并保持不变时-
- 搜索倒计时达到0,正在进行搜索。
为什么我需要(这样):
我有大型数据库的记录和使用ajax方法来获取通过。每次键上(搜索输入)发送请求…(这是一种资源浪费,而且每次按键刷新页面都让人不舒服)。所以我的方法是创建"typing ">-我的意思是描述上面。
Only纯JS没有图书馆!谢谢。
var timer=null;
document.getElementById("myInput").onkeyup = ()=>{
clearInterval(timer);
timer = setInterval(()=>{
console.log("call ajax search function here.");
clearInterval(timer);
},1000);
};
<input type="text" id="myInput">
你需要的是debounce函数
如果你不使用像lodash这样的库,你可以这样实现:
function debounce(f, ms) {
let isCooldown = false;
return function() {
if (isCooldown) return;
f.apply(this, arguments);
isCooldown = true;
setTimeout(() => isCooldown = false, ms);
};
}
那么你可以这样编码:
const handleSearch = (search) => {
// your logic with fetch or whatever
}
const handleSearchDebounced = debounce(handleSearch, 300)