无法使 _.debounce() 工作

Cannot get _.debounce() to work

我在尝试让 underscore.debounce() 工作时遇到问题。我在输入字段上附加了一个按键事件监听器。我将执行一些操作,然后调用未调用的 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));

Debounce returns 需要调用的函数,在这种情况下,您正在创建一个函数但从未调用它。试试这个:

// 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');
}