Refusal of work

See http://jsfiddle.net/5MvnA/2/ and the console.

There should be less Fs than Ks, but Fs is generally absent.

I got the debouncing code

function debounce(fn, delay) { var timer = null; return function () { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); }; } 

from here http://remysharp.com/2010/07/21/throttling-function-calls/

Remember if I check it wrong?

+4
source share
2 answers

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(); } 
+8
source

You must call the function returns from debounce . change the code to

 $('input').keyup( function() { console.log('k'); this.func = this.func || debounce(f, 100); this.func.apply( this, Array.prototype.slice.call(arguments) ); }); 
0
source

Source: https://habr.com/ru/post/1482207/


All Articles