仅在使用反跳功能时,发现这段似乎可以解决问题的代码:
$(document).ready(function() {
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function searchUsers () {
// some code irrelevant to this question (...)
};
var myEfficientFn = debounce(searchUsers, 450);
document.getElementById("search").addEventListener('input', myEfficientFn);
});
以上似乎效果很好。
但是我很好奇我是否可以直接将debounce
函数传递给addEventListener
而不是先将其保存在变量myEfficentFn
中。
所以我从代码中删除了行var myEfficientFn = debounce(searchUsers, 450);
并将最后一行更改为:
getElementById("search").addEventListener('input', function() {
debounce(searchUsers, 450);
});
但是它停止工作了。为什么?
答案 0 :(得分:1)
debounce
是一个函数,当被调用时,它会返回另一个函数,该事件在事件触发时会被调用,在您的原始代码中:
var myEfficientFn = debounce(searchUsers, 450);
document.getElementById("search").addEventListener('input', myEfficientFn);
相反,在第二个代码中,您是在事件监听器中的debounce
中调用。 debounce
返回一个函数,但是您永远不会调用它:with
debounce(searchUsers, 450);
您有一个未使用的函数表达式,有点像
const someVar = () => console.log('hi');
以后不再使用someVar
。
直接将debounce
调用(返回所需的事件侦听器函数)传递到addEventListener
中
document.getElementById("search").addEventListener('input', debounce(searchUsers, 450));
答案 1 :(得分:1)
其他答案遗漏了一些信息,可以帮助您了解正在发生的事情:
getElementById("search").addEventListener('input', function() { // <--- this function gets called on click
debounce(searchUsers, 450); // this is a function, not a function call
});
getElementById("search").addEventListener('input', function(ev) { // <--- this function gets called on click
debounce(searchUsers, 450)(ev); // this is how you call the function returned by debounce
});
答案 2 :(得分:1)
简短说明;
debounce
函数返回一个由事件侦听器运行的函数。
return function()
...
您的第一种方法是将返回的函数保存到一个变量中,然后均匀侦听器将其运行。
addEventListener('input', myEfficientFn);
...
您的第二种方法将返回的函数获取到另一个函数中,而没有人真正运行它。
debounce(searchUsers, 450); //WHo runs the returned function?
...
在您自己的上下文中解决方案-运行返回的函数!
getElementById("search").addEventListener('input', function(e) {
debounce(searchUsers, 450)(e);
});
答案 3 :(得分:0)
您不必将其包装在匿名函数中,只需使用:
.addEventListener('input', debounce(searchUsers, 450))