Your code should look like this
$('input').keyup( function() { console.log('k'); }); $('input').keyup(debounce(f, 100));
In your example, you never call the returned function and always create a new function.
Based on your comment. How to use it in a different context. The following example will write foo 10 times to the console, but add only one timestamp.
function debounce(fn, delay) { var timer = null; return function () { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); }; } function fnc () { console.log("Date: ",new Date()); } var myDebouncedFunction = debounce(fnc, 100); function foo() { console.log("called foo"); myDebouncedFunction(); } for ( var i=0; i<10; i++) { foo(); }
source share