我在尝试让underscore.debounce()工作时遇到了问题。我在一个输入字段上附加了一个keydown事件侦听器。我将执行一些操作,然后调用未被调用的debounce()。我想知道为什么它不工作?
我提供了两个示例。我没有将_.debounce()作为内联连接的第一个是不工作的。我附加了_.debounce()作为内联的第二个是工作的。我不明白为什么非内联解决方案是有效的?
// This example does not ever call _.debounce()
$('input').on('keydown', onKeyDown);
function onKeyDown() {
console.log('performing some actions...');
_.debounce(function() {
console.log('debouncing'); // never called
}, 500);
}
// This example does call _.debounce()
$('input').on('keydown', _.debounce(function() {
console.log('debounce');
}, 500));发布于 2017-12-21 01:38:42
Debounce返回一个需要调用的函数,在这种情况下,您正在创建一个函数,但从未调用过它。试试这个:
// This example does not ever call _.debounce()
var debounced = _.debounce(debounceStuff, 500);
$('input').on('keydown', onKeyDown);
function onKeyDown() {
console.log('performing some actions...');
debounced();
}
function debounceStuff() {
console.log('debouncing');
}https://stackoverflow.com/questions/47911459
复制相似问题