无法让_.debounce()工作

时间:2017-12-20 17:31:20

标签: javascript underscore.js

我无法尝试使用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));

1 个答案:

答案 0 :(得分:4)

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