lodash debounce not working in anonymous function - javascript

Hello I cannot seem to figure out why the debounce function works as expected when passed directly to a keyup event; but it does not work if I wrap it inside an anonymous function.
I have fiddle of the problem: http://jsfiddle.net/6hg95/1/
EDIT: Added all the things I tried.
HTML
<input id='anonFunction'/>
<input id='noReturnAnonFunction'/>
<input id='exeDebouncedFunc'/>
<input id='function'/>
<div id='output'></div>
JAVASCRIPT
$(document).ready(function(){
$('#anonFunction').on('keyup', function () {
return _.debounce(debounceIt, 500, false); //Why does this differ from #function
});
$('#noReturnAnonFunction').on('keyup', function () {
_.debounce(debounceIt, 500, false); //Not being executed
});
$('#exeDebouncedFunc').on('keyup', function () {
_.debounce(debounceIt, 500, false)(); //Executing the debounced function results in wrong behaviour
});
$('#function').on('keyup', _.debounce(debounceIt, 500, false)); //This is working.
});
function debounceIt(){
$('#output').append('debounced');
}
anonFunction and noReturnAnonFunction does not fire the debounce function; but the last function does fire. I do not understand why this is. Can anybody please help me understand this?
EDIT
Ok, so the reason that the debounce does not happen in #exeDebouncedFunc (the one you refer) is because the function is executed in the scope of the anonymous function and another keyup event will create a new function in another anonymous scope; thus firing the debounced function as many times as you type something (instead of firing once which would be the expected behaviour; see beviour of #function)?
Can you please explain the difference between #anonFunction and the #function. Is this again a matter of scoping why one of them works and the other does not?
EDIT
Ok, so now I understand why this is happening. And here is why I needed to wrap it inside an anonymous function:
Fiddle: http://jsfiddle.net/6hg95/5/
HTML
<input id='anonFunction'/>
<div id='output'></div>
JAVASCRIPT
(function(){
var debounce = _.debounce(fireServerEvent, 500, false);
$('#anonFunction').on('keyup', function () {
//clear textfield
$('#output').append('clearNotifications<br/>');
debounce();
});
function fireServerEvent(){
$('#output').append('serverEvent<br/>');
}
})();

As Palpatim explained, the reason lies in the fact that _.debounce(...) returns a function, which when invoked does its magic.
Therefore in your #anonFunction example, you have a key listener, which when invoked does nothing but return a function to the invoker, which does nothing with the return values from the event listener.
This is a snippet of the _.debounce(...) definition:
_.debounce
function (func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
if (immediate && !timeout) func.apply(context, args);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
Your key event listener must invoke the returned function from _.debounce(...), or you can do as in your non-anonymous example and use the returned function from the _.debounce(...) call as your event listener.

Think easier
_.debounce returns a debounced function!
So instead of thinking in terms of
$el.on('keyup'), function(){
_.debounce(doYourThing,500); //uh I want to debounce this
}
you rather call the debounced function instead
var doYourThingDebounced = _.debounce(doYourThing, 500); //YES, this will always be debounced
$el.on('keyup', doYourThingDebounced);

debounce doesn't execute the function, it returns a function with the debounciness built into it.
Returns
(Function): Returns the new debounced function.
So your #function handler is actually doing the Right Thing, by returning a function to be used by jQuery as a keyup handler. To fix your #noReturnAnonFunction example, you could simply execute the debounced function in the context of your function:
$('#noReturnAnonFunction').on('keyup', function () {
_.debounce(debounceIt, 500, false)(); // Immediately executes
});
But that's introducing a needless anonymous function wrapper around your debounce.

You can return the debounce function like this:
(function(){
var debounce = _.debounce(fireServerEvent, 500, false);
$('#anonFunction').on('keyup', function () {
//clear textfield
$('#output').append('clearNotifications<br/>');
return debounce();
});
function fireServerEvent(){
$('#output').append('serverEvent<br/>');
}
})();

Came across this while looking for a solution to calling a debounce with a trailing call, found this article which really helped me:
https://newbedev.com/lodash-debounce-not-working-in-react
specifically:
Solution for those who came here because throttle / debounce doesn't work >with FunctionComponent - you need to store debounced function via useRef():
export const ComponentName = (value = null) => {
const [inputValue, setInputValue] = useState(value);
const setServicesValue = value => Services.setValue(value);
const setServicesValueDebounced = useRef(_.debounce(setServicesValue, 1000));
const handleChange = ({ currentTarget: { value } }) => {
setInputValue(value);
setServicesValueDebounced.current(value);
};
return <input onChange={handleChange} value={inputValue} />;
};

More generally, if you want a debounce with a trailing behaviour (accounts for last click, or more likely last change on a select input), and a visual feedback on first click/change, you are faced with the same issue.
This does not work:
$(document).on('change', "#select", function() {
$('.ajax-loader').show();
_.debounce(processSelectChange, 1000);
});
This would be a solution:
$(document).on('change', "#select", function() {
$('.ajax-loader').show();
});
$(document).on('change', "#select", _.debounce(processSelectChange, 1000));

Related

Getting the ID of button from an onclick function [duplicate]

The situation is somewhat like-
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
The problem is that the value of someVar is not visible inside the listener function of the addEventListener, where it is probably being treated as a new variable.
Why not just get the arguments from the target attribute of the event?
Example:
const someInput = document.querySelector('button');
someInput.addEventListener('click', myFunc, false);
someInput.myParam = 'This is my parameter';
function myFunc(evt)
{
window.alert(evt.currentTarget.myParam);
}
<button class="input">Show parameter</button>
JavaScript is a prototype-oriented language, remember!
There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous
function() { some_function(someVar); }
was created.
Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
This question is old but I thought I'd offer an alternative using ES5's .bind() - for posterity. :)
function some_func(otherFunc, ev) {
// magic happens
}
someObj.addEventListener("click", some_func.bind(null, some_other_func), false);
Just be aware that you need to set up your listener function with the first param as the argument you're passing into bind (your other function) and the second param is now the event (instead of the first, as it would have been).
Quite and old question but I had the same issue today. Cleanest solution I found is to use the concept of currying.
The code for that:
someObj.addEventListener('click', some_function(someVar));
var some_function = function(someVar) {
return function curried_func(e) {
// do something here
}
}
By naming the curried function it allows you to call Object.removeEventListener to unregister the eventListener at a later execution time.
You can just bind all necessary arguments with 'bind':
root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));
In this way you'll always get the event, arg1, and other stuff passed to myPrettyHandler.
http://passy.svbtle.com/partial-application-in-javascript-using-bind
nice one line alternative
element.addEventListener('dragstart',(evt) => onDragStart(param1, param2, param3, evt));
function onDragStart(param1, param2, param3, evt) {
//some action...
}
You can add and remove eventlisteners with arguments by declaring a function as a variable.
myaudio.addEventListener('ended',funcName=function(){newSrc(myaudio)},false);
newSrc is the method with myaudio as parameter
funcName is the function name variable
You can remove the listener with
myaudio.removeEventListener('ended',func,false);
Function.prototype.bind() is the way to bind a target function to a particular scope and optionally define the this object within the target function.
someObj.addEventListener("click", some_function.bind(this), false);
Or to capture some of the lexical scope, for example in a loop:
someObj.addEventListener("click", some_function.bind(this, arg1, arg2), false);
Finally, if the this parameter is not needed within the target function:
someObj.addEventListener("click", some_function.bind(null, arg1, arg2), false);
You could pass somevar by value(not by reference) via a javascript feature known as closure:
var someVar='origin';
func = function(v){
console.log(v);
}
document.addEventListener('click',function(someVar){
return function(){func(someVar)}
}(someVar));
someVar='changed'
Or you could write a common wrap function such as wrapEventCallback:
function wrapEventCallback(callback){
var args = Array.prototype.slice.call(arguments, 1);
return function(e){
callback.apply(this, args)
}
}
var someVar='origin';
func = function(v){
console.log(v);
}
document.addEventListener('click',wrapEventCallback(func,someVar))
someVar='changed'
Here wrapEventCallback(func,var1,var2) is like:
func.bind(null, var1,var2)
Here's yet another way (This one works inside for loops):
var someVar = some_other_function();
someObj.addEventListener("click",
function(theVar){
return function(){some_function(theVar)};
}(someVar),
false);
someVar value should be accessible only in some_function() context, not from listener's.
If you like to have it within listener, you must do something like:
someObj.addEventListener("click",
function(){
var newVar = someVar;
some_function(someVar);
},
false);
and use newVar instead.
The other way is to return someVar value from some_function() for using it further in listener (as a new local var):
var someVar = some_function(someVar);
one easy way to execute that may be this
window.addEventListener('click', (e) => functionHandler(e, ...args));
Works for me.
$form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));
function save(data, keyword, name, comment, event) {
This is how I got event passed properly.
Use
el.addEventListener('click',
function(){
// this will give you the id value
alert(this.id);
},
false);
And if you want to pass any custom value into this anonymous function then the easiest way to do it is
// this will dynamically create property a property
// you can create anything like el.<your variable>
el.myvalue = "hello world";
el.addEventListener('click',
function(){
//this will show you the myvalue
alert(el.myvalue);
// this will give you the id value
alert(this.id);
},
false);
Works perfectly in my project. Hope this will help
If I'm not mistaken using calling the function with bind actually creates a new function that is returned by the bind method. This will cause you problems later or if you would like to remove the event listener, as it's basically like an anonymous function:
// Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', myCallback);
someObject.removeEventListener('event', myCallback);
// Not Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', function() { myCallback });
someObject.removeEventListener('event', /* can't remove anonymous function */);
So take that in mind.
If you are using ES6 you could do the same as suggested but a bit cleaner:
someObject.addEventListener('event', () => myCallback(params));
One way is doing this with an outer function:
elem.addEventListener('click', (function(numCopy) {
return function() {
alert(numCopy)
};
})(num));
This method of wrapping an anonymous function in parentheses and calling it right away is called an IIFE (Immediately-Invoked Function Expression)
You can check an example with two parameters in http://codepen.io/froucher/pen/BoWwgz.
catimg.addEventListener('click', (function(c, i){
return function() {
c.meows++;
i.textContent = c.name + '\'s meows are: ' + c.meows;
}
})(cat, catmeows));
In 2019, lots of api changes, the best answer no longer works, without fix bug.
share some working code.
Inspired by all above answer.
button_element = document.getElementById('your-button')
button_element.setAttribute('your-parameter-name',your-parameter-value);
button_element.addEventListener('click', your_function);
function your_function(event)
{
//when click print the parameter value
console.log(event.currentTarget.attributes.your-parameter-name.value;)
}
Sending arguments to an eventListener's callback function requires creating an isolated function and passing arguments to that isolated function.
Here's a nice little helper function you can use. Based on "hello world's" example above.)
One thing that is also needed is to maintain a reference to the function so we can remove the listener cleanly.
// Lambda closure chaos.
//
// Send an anonymous function to the listener, but execute it immediately.
// This will cause the arguments are captured, which is useful when running
// within loops.
//
// The anonymous function returns a closure, that will be executed when
// the event triggers. And since the arguments were captured, any vars
// that were sent in will be unique to the function.
function addListenerWithArgs(elem, evt, func, vars){
var f = function(ff, vv){
return (function (){
ff(vv);
});
}(func, vars);
elem.addEventListener(evt, f);
return f;
}
// Usage:
function doSomething(withThis){
console.log("withThis", withThis);
}
// Capture the function so we can remove it later.
var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");
// To remove the listener, use the normal routine:
someElem.removeEventListener("click", storeFunc);
There is a special variable inside all functions: arguments. You can pass your parameters as anonymous parameters and access them (by order) through the arguments variable.
Example:
var someVar = some_other_function();
someObj.addEventListener("click", function(someVar){
some_function(arguments[0]);
}, false);
I was stuck in this as I was using it in a loop for finding elements and adding listner to it. If you're using it in a loop, then this will work perfectly
for (var i = 0; i < states_array.length; i++) {
var link = document.getElementById('apply_'+states_array[i].state_id);
link.my_id = i;
link.addEventListener('click', function(e) {
alert(e.target.my_id);
some_function(states_array[e.target.my_id].css_url);
});
}
I suggest you to do something like that:
var someVar = some_other_function();
someObj.addEventListener("click", (event, param1 = someVar) => {
some_function(param1);
}, false);
The PERFECT SOLUTION for this is to use Closures like this:
function makeSizer(size) {
return function () {
document.body.style.fontSize = `${size}px`;
};
}
//pass parameters here and keep the reference in variables:
const size12 = makeSizer(12);
const size24 = makeSizer(24);
const size36 = makeSizer(36);
document.getElementById('size-12').addEventListener("click", size12);
document.getElementById('size-24').addEventListener("click", size24);
document.getElementById('size-36').addEventListener("click", size36);
document.getElementById('remove-12').addEventListener("click", ()=>{
document.getElementById('size-12').removeEventListener("click", size12);
alert("Now click on 'size 12' button and you will see that there is no event listener any more");
});
test<br/>
<button id="size-12">
size 12
</button>
<button id="size-24">
size 24
</button>
<button id="size-36">
size 36
</button>
<button id="remove-12">
remove 12
</button>
So basically you wrap a function inside another function and assign that to a variable that you can register as an event listener, but also unregister as well!
Also try these (IE8 + Chrome. I dont know for FF):
function addEvent(obj, type, fn) {
eval('obj.on'+type+'=fn');
}
function removeEvent(obj, type) {
eval('obj.on'+type+'=null');
}
// Use :
function someFunction (someArg) {alert(someArg);}
var object=document.getElementById('somObject_id') ;
var someArg="Hi there !";
var func=function(){someFunction (someArg)};
// mouseover is inactive
addEvent (object, 'mouseover', func);
// mouseover is now active
addEvent (object, 'mouseover');
// mouseover is inactive
Hope there is no typos :-)
The following answer is correct but the below code is not working in IE8 if suppose you compressed the js file using yuicompressor. (In fact,still most of the US peoples using IE8)
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click",
function(){
some_function(someVar);
},
false);
So, we can fix the above issue as follows and it works fine in all browsers
var someVar, eventListnerFunc;
someVar = some_other_function();
eventListnerFunc = some_function(someVar);
someObj.addEventListener("click", eventListnerFunc, false);
Hope, it would be useful for some one who is compressing the js file in production environment.
Good Luck!!
var EV = {
ev: '',
fn: '',
elem: '',
add: function () {
this.elem.addEventListener(this.ev, this.fn, false);
}
};
function cons() {
console.log('some what');
}
EV.ev = 'click';
EV.fn = cons;
EV.elem = document.getElementById('body');
EV.add();
//If you want to add one more listener for load event then simply add this two lines of code:
EV.ev = 'load';
EV.add();
The following approach worked well for me. Modified from here.
function callback(theVar) {
return function() {
theVar();
}
}
function some_other_function() {
document.body.innerHTML += "made it.";
}
var someVar = some_other_function;
document.getElementById('button').addEventListener('click', callback(someVar));
<!DOCTYPE html>
<html>
<body>
<button type="button" id="button">Click Me!</button>
</body>
</html>
Since your event listener is 'click', you can:
someObj.setAttribute("onclick", "function(parameter)");
Another workaround is by Using data attributes
function func(){
console.log(this.dataset.someVar);
div.removeEventListener("click", func);
}
var div = document.getElementById("some-div");
div.setAttribute("data-some-var", "hello");
div.addEventListener("click", func);
jsfiddle
The following code worked fine for me (firefox):
for (var i=0; i<3; i++) {
element = new ... // create your element
element.counter = i;
element.addEventListener('click', function(e){
console.log(this.counter);
... // another code with this element
}, false);
}
Output:
0
1
2
You need:
newElem.addEventListener('click', {
handleEvent: function (event) {
clickImg(parameter);
}
});

Run a function inside an anonymous function inside event listener

Just working on debounce feature and found this piece of code that seems to be doing the trick:
$(document).ready(function() {
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function searchUsers () {
// some code irrelevant to this question (...)
};
var myEfficientFn = debounce(searchUsers, 450);
document.getElementById("search").addEventListener('input', myEfficientFn);
});
Above seem to work well.
But I was curious if I can pass debounce function straight to addEventListener instead of saving it first in a variable myEfficentFn.
So I removed line var myEfficientFn = debounce(searchUsers, 450); from code and changed the last line to:
getElementById("search").addEventListener('input', function() {
debounce(searchUsers, 450);
});
but it stopped working. Why?
debounce is a function that, when called, returns another function, one which in your original code, is called when the event triggers:
var myEfficientFn = debounce(searchUsers, 450);
document.getElementById("search").addEventListener('input', myEfficientFn);
In contrast, in your second code, you're calling debounce inside the event listener. debounce returns a function, but you're never calling it: with
debounce(searchUsers, 450);
you have an unused function expression, kind of like having
const someVar = () => console.log('hi');
without ever using someVar later.
Pass the debounce call (which returns the function you want as the event listener) directly into addEventListener instead:
document.getElementById("search").addEventListener('input', debounce(searchUsers, 450));
The other answers left out a little bit of info that would help you understand what's happening:
getElementById("search").addEventListener('input', function() { // <--- this function gets called on click
debounce(searchUsers, 450); // this is a function, not a function call
});
getElementById("search").addEventListener('input', function(ev) { // <--- this function gets called on click
debounce(searchUsers, 450)(ev); // this is how you call the function returned by debounce
});
A short explanation;
The debounce function returns a function which is run by the event listener.
return function()
...
Your first approach saves the returned function to a variable and the even listener runs it.
addEventListener('input', myEfficientFn);
...
Your second approach gets the returned function within another function and no one really runs it.
debounce(searchUsers, 450); //WHo runs the returned function?
...
Solution in your own context - run the returned function!
getElementById("search").addEventListener('input', function(e) {
debounce(searchUsers, 450)(e);
});
you don't have to wrap it inside an anonymous function, you can simply use:
.addEventListener('input', debounce(searchUsers, 450))

Run JavaScript immediately but wait x seconds before it can be run again?

Im listening for an event and I need to run a function (in this example console log for demoing my code) when it happens.
This is working however the event happens multiple times in quick succession and I only want the function to run once. How can I run the function straight away but then wait a second before its able to be triggered again?
$(document).on('someEvent', function(event, data) {
if (var === 'something') {
console.log('Run');
}
});
Update: To be clear, I need to wait for the event 'someEvent' to occur before my console function runs.
Some like that?
var is_blocked = false;
var block = function( time_to_wait ) {
is_blocked = true;
setTimeout( function() {
is_blocked = false;
}, time_to_wait );
};
$(document).on('someEvent', function(event, data) {
if ( is_blocked === false ) {
block( 1000 );
console.log('Run');
}
});
If you don't mind using an external library, use lodash's debounce method. Note that the sample in the docs is pretty similar to the case you described. The options (leading/trailing) can be used to customize the behavior.
There's a tiny library called underscore.js that has a ton of useful functions. Among these there is _.debounce:
debounce_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function
which will postpone its execution until after wait milliseconds have
elapsed since the last time it was invoked. Useful for implementing
behavior that should only happen after the input has stopped arriving.
For example: rendering a preview of a Markdown comment, recalculating
a layout after the window has stopped being resized, and so on.
Pass true for the immediate argument to cause debounce to trigger the
function on the leading instead of the trailing edge of the wait
interval. Useful in circumstances like preventing accidental
double-clicks on a "submit" button from firing a second time.
In your case it's a matter of wrapping the handler function like this (I used 100ms for the timeout):
$(document).on('someEvent', _.debounce(function(event, data) {
if (var === 'something') {
console.log('Run');
}
}, 100));
Function "functionToBeCalled()" will be executed immediately, and every 0.4 seconds. If you want to call again that function after 0.4s and not every time replace setInterval with setTimeout.
var variable = "something";
$("#button").on('click', function(event, data) {
if ( variable === 'something') {
console.log('Run');
setTimeout(function(){
$("#button").trigger("click");
}, 1000)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button">Button</div>
You could use the current time:
var waitUntil = Date.now();
$(document).on('someEvent', function(event, data) {
if (Date.now() >= waitUntil) {
waitUntil = Date.now() + 5000 // 5 seconds wait from now
console.log('Run');
}
});
Here is a fiddle which uses a button click as the event, and gives feed-back on-screen about whether the event is treated or not.
Here's a neat little function that might help:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args);
};
}

jQuery - delaying all functions calls declared with .on

I am using the .on() function in jQuery to assign functions to events.
var someEvent = getEventName(someParams); // gets the event, like 'click'
var someFunctionReference = getFunctionNameBasedOnParams(someParams); // gets the function reference
$('.myElement').on(someEvent, someFunctionReference);
What I would like to do is wrap 'someFunctionReference' inside a timeout or delay its firing (by some time; lets say 250ms) without having to go and modify every single function that is returned by the method.
Is there a way to do this?
I'll assume you can't modify the code in getFunctionNameBasedOnParams, so all you need to do is create another function that returns a function wrapped in a timer.
function delayFunc(fn, ms) {
return function() {
var args = arguments;
setTimeout(function() {
fn.apply(this, args);
}, isNaN(ms) ? 100 : ms);
}
}
Then pass your function to it.
var someFunctionReference = delayFunc(getFunctionNameBasedOnParams(someParams), 250);
Be aware that your handler's return value is now meaningless, so if you return false, it'll have no effect.

Select the first field from jQuery autocomplete function automatically

When I mouseover a field in my autocomplete list it adds a class named selected. I want it to do that by default on the first line as soon as you start typing. How would i select the first element in that list and change it's class?
I'm using this now but it flickers a lot.
$('.name').eq(0).addClass('selected');
You may want to use jQuery's toggleClass() and first() for that.
$('.name').first().toggleClass('selected');
I'm betting the flicker is caused by calling it on every keyup event. You need to 'debounce' the function call.
Debouncing functions with jQuery:
http://benalman.com/projects/jquery-throttle-debounce-plugin/
Like this:
$('input:text').keyup( $.debounce( 250, function() {
// run autocomplete routine / ajax call here
$('.name').eq(0).addClass('selected');
}) );
That requires a jQuery plugin of course, so if you'd rather have a minimal-footprint version, use John Hann's pure-Javascript version:
Debouncing functions with pure Javascript and less code:
Or if you don't want to use another plugin, debouncing is as easy as:
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
};
Usage:
$('input:text').keyup( debounce(function() {
// run autocomplete routine / ajax call here
$('.name').eq(0).addClass('selected');
}), 250, false );

Categories