一种可能的解决方法是在搜索框的键盘事件中添加一个防抖函数,以防止过多的API请求并在用户打字时卡住搜索框。以下是一个基本的示例:
// 设置搜索框元素
const searchBox = document.querySelector('#search-box');
// 设置防抖等待时间
const debounceTime = 300;
// 设置防抖函数
const debounce = (func, wait) => {
let timeout;
return function executedFunc(...args) {
const context = this;
const later = () => {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
// 在搜索框上添加键盘事件监听器
searchBox.addEventListener('keyup', debounce(() => {
// Algolia搜索代码
}, debounceTime));