jQuery - delaying all functions calls declared with .on - javascript

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.

Related

How can I prevent firing setTimeout function if user performs actions too fast in js? [duplicate]

I am interested in the "debouncing" function in JavaScript, at JavaScript Debounce Function.
Unfortunately the code is not explained clearly enough for me to understand. How does it work (I left my comments below)? In short, I just really do not understand how this works.
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
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);
};
};
The copied code snippet previously had callNow in the wrong spot.
The code in the question was altered slightly from the code in the link. In the link, there is a check for (immediate && !timeout) before creating a new time-out. Having it after causes immediate mode to never fire. I have updated my answer to annotate the working version from the link.
function debounce(func, wait, immediate) {
// 'private' variable for instance
// The returned function will be able to reference this due to closure.
// Each call to the returned function will share this common timer.
var timeout;
// Calling debounce returns a new anonymous function
return function() {
// reference the context and args for the setTimeout function
var context = this,
args = arguments;
// Should the function be called now? If immediate is true
// and not already in a timeout then the answer is: Yes
var callNow = immediate && !timeout;
// This is the basic debounce behaviour where you can call this
// function several times, but it will only execute once
// (before or after imposing a delay).
// Each time the returned function is called, the timer starts over.
clearTimeout(timeout);
// Set the new timeout
timeout = setTimeout(function() {
// Inside the timeout function, clear the timeout variable
// which will let the next execution run when in 'immediate' mode
timeout = null;
// Check if the function already ran with the immediate flag
if (!immediate) {
// Call the original function with apply
// apply lets you define the 'this' object as well as the arguments
// (both captured before setTimeout)
func.apply(context, args);
}
}, wait);
// Immediate mode and no wait timer? Execute the function...
if (callNow) func.apply(context, args);
}
}
/////////////////////////////////
// DEMO:
function onMouseMove(e){
console.clear();
console.log(e.x, e.y);
}
// Define the debounced function
var debouncedMouseMove = debounce(onMouseMove, 50);
// Call the debounced function on every mouse move
window.addEventListener('mousemove', debouncedMouseMove);
The important thing to note here is that debounce produces a function that is "closed over" the timeout variable. The timeout variable stays accessible during every call of the produced function even after debounce itself has returned, and can change over different calls.
The general idea for debounce is the following:
Start with no timeout.
If the produced function is called, clear and reset the timeout.
If the timeout is hit, call the original function.
The first point is just var timeout;, it is indeed just undefined. Luckily, clearTimeout is fairly lax about its input: passing an undefined timer identifier causes it to just do nothing, it doesn't throw an error or something.
The second point is done by the produced function. It first stores some information about the call (the this context and the arguments) in variables so it can later use these for the debounced call. It then clears the timeout (if there was one set) and then creates a new one to replace it using setTimeout. Note that this overwrites the value of timeout and this value persists over multiple function calls! This allows the debounce to actually work: if the function is called multiple times, timeout is overwritten multiple times with a new timer. If this were not the case, multiple calls would cause multiple timers to be started which all remain active - the calls would simply be delayed, but not debounced.
The third point is done in the timeout callback. It unsets the timeout variable and does the actual function call using the stored call information.
The immediate flag is supposed to control whether the function should be called before or after the timer. If it is false, the original function is not called until after the timer is hit. If it is true, the original function is first called and will not be called any more until the timer is hit.
However, I do believe that the if (immediate && !timeout) check is wrong: timeout has just been set to the timer identifier returned by setTimeout so !timeout is always false at that point and thus the function can never be called. The current version of underscore.js seems to have a slightly different check, where it evaluates immediate && !timeout before calling setTimeout. (The algorithm is also a bit different, e.g. it doesn't use clearTimeout.) That's why you should always try to use the latest version of your libraries. :-)
Debounced functions do not execute when invoked. They wait for a pause of invocations over a configurable duration before executing; each new invocation restarts the timer.
Throttled functions execute and then wait a configurable duration before being eligible to fire again.
Debounce is great for keypress events; when the user starts typing and then pauses you submit all the key presses as a single event, thus cutting down on the handling invocations.
Throttle is great for real-time endpoints that you only want to allow the user to invoke once per a set period of time.
Check out Underscore.js for their implementations too.
I too didn't fully understand how a debounce function worked when I first encountered one. Although relatively small in size, they actually employ some pretty advanced JavaScript concepts! Having a good grip on scope, closures and the setTimeout method will help.
With that said, below is the basic debounce function explained and demoed in my post referenced above.
The finished product
// Create JD Object
// ----------------
var JD = {};
// Debounce Method
// ---------------
JD.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);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait || 200);
if ( callNow ) {
func.apply(context, args);
}
};
};
The explanation
// Create JD Object
// ----------------
/*
It's a good idea to attach helper methods like `debounce` to your own
custom object. That way, you don't pollute the global space by
attaching methods to the `window` object and potentially run in to
conflicts.
*/
var JD = {};
// Debounce Method
// ---------------
/*
Return a function, that, as long as it continues to be invoked, will
not be triggered. The function will be called after it stops being
called for `wait` milliseconds. If `immediate` is passed, trigger the
function on the leading edge, instead of the trailing.
*/
JD.debounce = function(func, wait, immediate) {
/*
Declare a variable named `timeout` variable that we will later use
to store the *timeout ID returned by the `setTimeout` function.
*When setTimeout is called, it retuns a numeric ID. This unique ID
can be used in conjunction with JavaScript's `clearTimeout` method
to prevent the code passed in the first argument of the `setTimout`
function from being called. Note, this prevention will only occur
if `clearTimeout` is called before the specified number of
milliseconds passed in the second argument of setTimeout have been
met.
*/
var timeout;
/*
Return an anomymous function that has access to the `func`
argument of our `debounce` method through the process of closure.
*/
return function() {
/*
1) Assign `this` to a variable named `context` so that the
`func` argument passed to our `debounce` method can be
called in the proper context.
2) Assign all *arugments passed in the `func` argument of our
`debounce` method to a variable named `args`.
*JavaScript natively makes all arguments passed to a function
accessible inside of the function in an array-like variable
named `arguments`. Assinging `arguments` to `args` combines
all arguments passed in the `func` argument of our `debounce`
method in a single variable.
*/
var context = this, /* 1 */
args = arguments; /* 2 */
/*
Assign an anonymous function to a variable named `later`.
This function will be passed in the first argument of the
`setTimeout` function below.
*/
var later = function() {
/*
When the `later` function is called, remove the numeric ID
that was assigned to it by the `setTimeout` function.
Note, by the time the `later` function is called, the
`setTimeout` function will have returned a numeric ID to
the `timeout` variable. That numeric ID is removed by
assiging `null` to `timeout`.
*/
timeout = null;
/*
If the boolean value passed in the `immediate` argument
of our `debouce` method is falsy, then invoke the
function passed in the `func` argument of our `debouce`
method using JavaScript's *`apply` method.
*The `apply` method allows you to call a function in an
explicit context. The first argument defines what `this`
should be. The second argument is passed as an array
containing all the arguments that should be passed to
`func` when it is called. Previously, we assigned `this`
to the `context` variable, and we assigned all arguments
passed in `func` to the `args` variable.
*/
if ( !immediate ) {
func.apply(context, args);
}
};
/*
If the value passed in the `immediate` argument of our
`debounce` method is truthy and the value assigned to `timeout`
is falsy, then assign `true` to the `callNow` variable.
Otherwise, assign `false` to the `callNow` variable.
*/
var callNow = immediate && !timeout;
/*
As long as the event that our `debounce` method is bound to is
still firing within the `wait` period, remove the numerical ID
(returned to the `timeout` vaiable by `setTimeout`) from
JavaScript's execution queue. This prevents the function passed
in the `setTimeout` function from being invoked.
Remember, the `debounce` method is intended for use on events
that rapidly fire, ie: a window resize or scroll. The *first*
time the event fires, the `timeout` variable has been declared,
but no value has been assigned to it - it is `undefined`.
Therefore, nothing is removed from JavaScript's execution queue
because nothing has been placed in the queue - there is nothing
to clear.
Below, the `timeout` variable is assigned the numerical ID
returned by the `setTimeout` function. So long as *subsequent*
events are fired before the `wait` is met, `timeout` will be
cleared, resulting in the function passed in the `setTimeout`
function being removed from the execution queue. As soon as the
`wait` is met, the function passed in the `setTimeout` function
will execute.
*/
clearTimeout(timeout);
/*
Assign a `setTimout` function to the `timeout` variable we
previously declared. Pass the function assigned to the `later`
variable to the `setTimeout` function, along with the numerical
value assigned to the `wait` argument in our `debounce` method.
If no value is passed to the `wait` argument in our `debounce`
method, pass a value of 200 milliseconds to the `setTimeout`
function.
*/
timeout = setTimeout(later, wait || 200);
/*
Typically, you want the function passed in the `func` argument
of our `debounce` method to execute once *after* the `wait`
period has been met for the event that our `debounce` method is
bound to (the trailing side). However, if you want the function
to execute once *before* the event has finished (on the leading
side), you can pass `true` in the `immediate` argument of our
`debounce` method.
If `true` is passed in the `immediate` argument of our
`debounce` method, the value assigned to the `callNow` variable
declared above will be `true` only after the *first* time the
event that our `debounce` method is bound to has fired.
After the first time the event is fired, the `timeout` variable
will contain a falsey value. Therfore, the result of the
expression that gets assigned to the `callNow` variable is
`true` and the function passed in the `func` argument of our
`debounce` method is exected in the line of code below.
Every subsequent time the event that our `debounce` method is
bound to fires within the `wait` period, the `timeout` variable
holds the numerical ID returned from the `setTimout` function
assigned to it when the previous event was fired, and the
`debounce` method was executed.
This means that for all subsequent events within the `wait`
period, the `timeout` variable holds a truthy value, and the
result of the expression that gets assigned to the `callNow`
variable is `false`. Therefore, the function passed in the
`func` argument of our `debounce` method will not be executed.
Lastly, when the `wait` period is met and the `later` function
that is passed in the `setTimeout` function executes, the
result is that it just assigns `null` to the `timeout`
variable. The `func` argument passed in our `debounce` method
will not be executed because the `if` condition inside the
`later` function fails.
*/
if ( callNow ) {
func.apply(context, args);
}
};
};
we're all using Promises now
Many implementations I've seen over-complicate the problem or have other hygiene issues. It's 2021 and we've been using Promises for a long time now – and for good reason, too. Promises clean up asynchronous programs and reduce the opportunities for mistakes to happen. In this post we will write our own debounce. This implementation will -
have at most one promise pending at any given time (per debounced task)
stop memory leaks by properly cancelling pending promises
resolve only the latest promise
demonstrate proper behaviour with live code demos
We write debounce with its two parameters, the task to debounce, and the amount of milliseconds to delay, ms. We introduce a single local binding for its local state, t -
function debounce (task, ms) {
let t = { promise: null, cancel: _ => void 0 }
return async (...args) => {
try {
t.cancel()
t = deferred(ms)
await t.promise
await task(...args)
}
catch (_) { /* prevent memory leak */ }
}
}
We depend on a reusable deferred function, which creates a new promise that resolves in ms milliseconds. It introduces two local bindings, the promise itself, an the ability to cancel it -
function deferred (ms) {
let cancel, promise = new Promise((resolve, reject) => {
cancel = reject
setTimeout(resolve, ms)
})
return { promise, cancel }
}
click counter example
In this first example, we have a button that counts the user's clicks. The event listener is attached using debounce, so the counter is only incremented after a specified duration -
// debounce, deferred
function debounce (task, ms) { let t = { promise: null, cancel: _ => void 0 }; return async (...args) => { try { t.cancel(); t = deferred(ms); await t.promise; await task(...args); } catch (_) { console.log("cleaning up cancelled promise") } } }
function deferred (ms) { let cancel, promise = new Promise((resolve, reject) => { cancel = reject; setTimeout(resolve, ms) }); return { promise, cancel } }
// dom references
const myform = document.forms.myform
const mycounter = myform.mycounter
// event handler
function clickCounter (event) {
mycounter.value = Number(mycounter.value) + 1
}
// debounced listener
myform.myclicker.addEventListener("click", debounce(clickCounter, 1000))
<form id="myform">
<input name="myclicker" type="button" value="click" />
<output name="mycounter">0</output>
</form>
live query example, "autocomplete"
In this second example, we have a form with a text input. Our search query is attached using debounce -
// debounce, deferred
function debounce (task, ms) { let t = { promise: null, cancel: _ => void 0 }; return async (...args) => { try { t.cancel(); t = deferred(ms); await t.promise; await task(...args); } catch (_) { console.log("cleaning up cancelled promise") } } }
function deferred (ms) { let cancel, promise = new Promise((resolve, reject) => { cancel = reject; setTimeout(resolve, ms) }); return { promise, cancel } }
// dom references
const myform = document.forms.myform
const myresult = myform.myresult
// event handler
function search (event) {
myresult.value = `Searching for: ${event.target.value}`
}
// debounced listener
myform.myquery.addEventListener("keypress", debounce(search, 1000))
<form id="myform">
<input name="myquery" placeholder="Enter a query..." />
<output name="myresult"></output>
</form>
multiple debounces, react hook useDebounce
In another Q&A someone asks if its possible to use expose the debounce cancellation mechanism and create a useDebounce React hook. Using deferred above, it's a trivial exercise.
// revised implementation
function debounce(task, ms) {
let t = { promise: null, cancel: _ => void 0 }
return [
// ...,
_ => t.cancel() // ✅ return cancellation mechanism
]
}
// revised usage
const [inc, cancel] = debounce(clickCounter, 1000) // ✅ two controls
myform.mybutton.addEventListener("click", inc)
myform.mycancel.addEventListener("click", cancel)
Implementing a useDebounce React hook is a breeze -
function useDebounce(task, ms) {
const [f, cancel] = debounce(task, ms)
useEffect(_ => cancel) // ✅ auto-cancel when component unmounts
return [f, cancel]
}
Head over to the original Q&A for a complete demo
A simple debounce function:
HTML:
<button id='myid'>Click me</button>
JavaScript:
function debounce(fn, delay) {
let timeoutID;
return function(...args) {
if(timeoutID)
clearTimeout(timeoutID);
timeoutID = setTimeout(() => {
fn(...args)
}, delay);
}
}
document.getElementById('myid').addEventListener('click', debounce(() => {
console.log('clicked');
}, 2000));
This is a variation which always fires the debounced function the first time it is called, with more descriptively named variables:
function debounce(fn, wait = 1000) {
let debounced = false;
let resetDebouncedTimeout = null;
return function(...args) {
if (!debounced) {
debounced = true;
fn(...args);
resetDebouncedTimeout = setTimeout(() => {
debounced = false;
}, wait);
} else {
clearTimeout(resetDebouncedTimeout);
resetDebouncedTimeout = setTimeout(() => {
debounced = false;
fn(...args);
}, wait);
}
}
};
You want to do the following: If you try to call a function right after another, the first should be cancelled and the new one should wait for a given timeout and then execute. So in effect you need some way of cancelling the timeout of the first function? But how?
You could call the function, and pass the returning timeout-id and then pass that ID into any new functions. But the solution above is way more elegant.
It effectively makes the timeout variable available in the scope of returned function. So when a 'resize' event is fired, it does not call debounce() again, hence the timeout content is not changed (!) and is still available for the "next function call".
The key thing here is basically that we call the internal function every time we have a resize event. Perhaps it is more clear if we imagine all resize-events is in an array:
var events = ['resize', 'resize', 'resize'];
var timeout = null;
for (var i = 0; i < events.length; i++){
if (immediate && !timeout)
func.apply(this, arguments);
clearTimeout(timeout); // Does not do anything if timeout is null.
timeout = setTimeout(function(){
timeout = null;
if (!immediate)
func.apply(this, arguments);
}
}
You see the timeout is available to the next iteration?
And there is no reason, in my opinion to rename this to content and arguments to args.
A simple debounce method in JavaScript:
Basic HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Debounce Method</title>
</head>
<body>
<button type="button" id="debounce">Debounce Method</button><br />
<span id="message"></span>
</body>
</html>
JavaScript file
var debouncebtn = document.getElementById('debounce');
function debounce(func, delay) {
var debounceTimer;
return function () {
var context = this, args = arguments;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(function() {
func.apply(context, args)
}, delay);
}
}
Driver code
debouncebtn.addEventListener('click', debounce(function() {
document.getElementById('message').innerHTML += '<br/> The button only triggers every 3 seconds how much every you fire an event';
console.log('The button only triggers every 3 seconds how much every you fire an event');
}, 3000))
Runtime example JSFiddle: https://jsfiddle.net/arbaazshaikh919/d7543wqe/10/
Below is a summary of what a debounce function does, explained in a couple of lines with a demo.
A debounce function is a function that will:
at its first execution, schedule the wrapped function to execute after an interval of time with the setTimeout function
(if executed again during this interval):
delete the previous schedule (with the clearTimeOut function)
reschedule a new one (with the setTimeout function)
And the cycle goes on until the interval of time has elapsed and the wrapped function executes.
Adapted from all comments and from this article
function debounce(callBack, interval, leadingExecution) {
// the schedule identifier, if it's not null/undefined, a callBack function was scheduled
let timerId;
return function () {
// Does the previous run has schedule a run
let wasFunctionScheduled = (typeof timerId === 'number');
// Delete the previous run (if timerId is null, it does nothing)
clearTimeout(timerId);
// Capture the environment (this and argument) and wraps the callback function
let funcToDebounceThis = this, funcToDebounceArgs = arguments;
let funcToSchedule = function () {
// Reset/delete the schedule
clearTimeout(timerId);
timerId = null;
// trailing execution happens at the end of the interval
if (!leadingExecution) {
// Call the original function with apply
callBack.apply(funcToDebounceThis, funcToDebounceArgs);
}
}
// Schedule a new execution at each execution
timerId = setTimeout(funcToSchedule, interval);
// Leading execution
if (!wasFunctionScheduled && leadingExecution) callBack.apply(funcToDebounceThis, funcToDebounceArgs);
}
}
function onMouseMove(e) {
console.log(new Date().toLocaleString() + ": Position: x: " + e.x + ", y:" + e.y);
}
let debouncedMouseMove = debounce(onMouseMove, 500);
document.addEventListener('mousemove', debouncedMouseMove);
If you are using react.js
function debounce(func, delay = 600) {
return (args) => {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
func(args);
}, delay);
};
}
const triggerSearch = debounce(handleSearch);
// Event which triggers search.
onSearch={(searchedValue) => {
setSearchedText(searchedValue);// state update
triggerSearch(searchedValue);
}}
Due this state update in the search event which gets triggered on each letter type, this was re-rendering, and all the code with the debounce func was also getting re initiated.
Due to this behaviour of react there was never an active timeout.
function debounce(func, delay = 600) {
return (args) => {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
func(args);
}, delay);
};
}
const triggerSearch = debounce(handleSearch);
To fix that i used a ref named timeout.
const timeout = useRef();

Why does setInterval initiate when I'm only assigning it?

I'm assigning to a variable, a function that uses setInterval, but I don't want the function to run until I call it. However, the function is running from just the assignment statement.
sessionClock = setInterval(function() {
console.log("Hi")
}, 1000)
I have also tried like this:
sayHi = function() {
console.log("Hi");
}
var sayHiStarter = setInterval(sayHi, 1000);
Both of these initiate the function and will log "Hi" to the console.
Why is it running on assignment? And what can do I do fix this?
If you only want to bind a function to setInterval, but call it later, you can use bind:
var sessionClock = setInterval.bind(null, function() {
console.log("Hi")
}, 1000);
//... later
var myInterval = sessionClock(); // start the timer
// ... later if you need to clear it
clearInterval(myInterval);
In principle, bind returns a new function that calls your original function (in this case, setInterval) with predefined arguments. So when you call sessionClock, that returned function is called. There a other aspects to bind, but they don't seem to apply in this context.
The call to setInterval does not return a function, but an identification for the created interval. This id is used to remove the interval when you don't want it to execute anymore:
sessionClock = setInterval(function() {
console.log("Hi")
}, 1000)
...
clearInterval(sessionclock);
What you want is something like this:
sessionClock = function () {
return setInterval(function() {
console.log("Hi")
},
1000);
}
//When needed
var intervalId=sessionClock();

lodash debounce not working in anonymous function

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

Remove anonymous event listeners before adding any new ones

EDIT : I need to invoke one function which fetches data and reloads the page's contents. But this has to be invoked once another function has fetched data(webSql). I cannot use the WebSql callback as variables are out of scope. So I created a custom Event and added a listener in the second function scope. So when data is fetched I am dispatching the event in the first function scope. Now the issue if the page was reloaded more than once, listeners will get added multiple times and all will be invoked which I dont want.
I need to make sure that only one function is listening to a custom event. Right now am removing the listener once its invoked like this :
document.addEventListener("customEvent", function () {
actualCallBack(var1, var2); // Since I need to pass parameters I need to use callBack within an anonymous function.
this.removeEventListener("customEvent", arguments.callee, false);
}, false);
But the problem is anonymous function will be removed only after its invoked in the first place. There is a possibility of listener getting added mulitple times. How can I remove event listeners before adding a new one ?
document.removeEventListener("customEvent");
document.addEventListener(...);
I could have removed it, if a variable function was used instead, but I need to pass some parameters to callback so I need to use anonymous functions.
using felix's suggestion
var setSingletonEventListener = (function(element){
var handlers = {};
return function(evtName, func){
handlers.hasOwnProperty(evtName) && element.removeEventListener(evtName, handlers[evtName]);
if (func) {
handlers[evtName] = func;
element.addEventListener(evtName, func);
} else {
delete handlers[evtName];
}
};
})(document);
setSingletonEventListener("custom event", function(){
});
//replaces the previous
setSingletonEventListener("custom event", function(){
});
//removes the listener, if any
setSingletonEventListener("custom event");
Here's one way:
var singletonEventListenerFor = function (element, eventName) {
var callback = null;
element.addEventListener(eventName, function () {
callback && callback();
});
return function (set) {
callback = set;
};
};
Testing:
var event = document.createEvent("Event");
event.initEvent("customEvent", true, true);
var listener = singletonEventListenerFor(document, "customEvent");
var counter = 0;
listener(function () {
console.log(++counter);
});
// counter === 1
document.dispatchEvent(event);
// Remove the listener
listener();
// This shouldn't increment counter.
document.dispatchEvent(event);
listener(function () {
console.log(++counter);
});
// counter === 2
document.dispatchEvent(event);
// counter === 3
document.dispatchEvent(event);
console.log('3 === ' + counter);
http://jsfiddle.net/Dogbert/2zUZT/
API could be improved by returning an object with .set(callback) and .remove() functions instead of using a single function to do both things, if you like.
Store somewhere that you've already applied the listener, and only add it, if it hasn't been added already.

JavaScript self invoking function

I'm trying to understand this example code, what is the function of line 15, why start(timeout)? (Sorry, I'm new to programming)
var schedule = function (timeout, callbackfunction) {
return {
start: function () {
setTimeout(callbackfunction, timeout)
}
};
};
(function () {
var timeout = 1000; // 1 second
var count = 0;
schedule(timeout, function doStuff() {
console.log(++count);
schedule(timeout, doStuff);
}).start(timeout);
})();
// "timeout" and "count" variables
// do not exist in this scope.
...why start(timeout)?
In that example, there's actually no reason for passing timeout into start, since start doesn't accept or use any arguments. The call may as well be .start().
What's happening is that schedule returns an object the schedule function creates, and one of the properties on that object is called start, which is a function. When start is called, it sets up a timed callback via setTimeout using the original timeout passed into schedule and the callback function passed into schedule.
The code calling schedule turns around and immediately calls the start function on the object it creates.
In the comments, Pointy points out (well, he would, wouldn't he?) that the callback function is calling schedule but not doing anything with the returned object, which is pointless — schedule doesn't do anything other than create and return the object, so not using the returned object makes the call pointless.
Here's the code with those two issues addressed:
var schedule = function (timeout, callbackfunction) {
return {
start: function () {
setTimeout(callbackfunction, timeout)
}
};
};
(function () {
var timeout = 1000; // 1 second
var count = 0;
schedule(timeout, function doStuff() {
console.log(++count);
schedule(timeout, doStuff).start(); // <== Change here
}).start(); // <== And here
})();
It's not very good code, though, frankly, even with the fixes. There's no particularly good reason for creating a new object every time, and frankly if the book is meant to be teaching, this example could be a lot clearer. Inline named function expressions and calls to methods on objects returned by a function...absolutely fine, but not for teaching. Still, I don't know the context, so those comments come with a grain of salt.
Here's a reworked version of using the schedule function by reusing the object it returns, and being clear about what bit is happening when:
(function () {
var timeout = 1000; // 1 second
var count = 0;
// Create the schedule object
var scheduleObject = schedule(timeout, doStuff);
// Set up the first timed callback
scheduleObject.start();
// This is called by each timed callback
function doStuff() {
// Show the count
console.log(++count);
// Set up the next timed callback
scheduleObject.start();
}
})();
The function schedule is executed as a function. That function returns an object. Like you can see with the { start... }. With the returned object it calls out the start function. This is called chaining. So the start function is executed after is set the function.
What is strange is that the timeout is passed to the start function which has no parameters.

Categories