Every example of a debounce function that I've seen so far prevents an action from happening multiple times for a specified time span, and then executes the action one time when the specified time span has elapsed, then resets the timer. For example, the $mdUtil.debounce
function that is included in Angular Material.
What I'm looking for is a debounce function that executes the action immediately and then prevents subsequent multiple actions from firing until the timer resets. This has the benefit of the user not having to wait until the debounce time has elapsed until their action is taken while still achieving the goal of debouncing the actions.
Has anyone seen one or had luck creating one?
Update After some more thought, the debounce function should fire the action immediately and then, if the debounced function was called again within the debounce time span, it should fire the action a second time before resetting the timer in case the second call changed any values.
The debounce is a special function that handles two tasks: 1 Allocating a scope for the timer variable 2 Scheduling your function to be triggered at a specific time More ...
Our function accepts two arguments, first a function to execute, and the second argument is the delay in milliseconds. In the first run, when the debounce function is called, we call the setTimeout () function to create a delay and once the timeout is complete, we execute the function.
From start to finish, it only takes 7 lines of code to implement a debounce function. The rest of this section focuses on those 7 lines of code so that we can see how our debounce function works internally. Starting with line 1, we've declared a new function named debounce. This new function has two parameters, callback and delay.
In the first run, when the debounce function is called, we call the setTimeout () function to create a delay and once the timeout is complete, we execute the function. If the debounce function is called between the delay, we simply reset the timer and create a new delay using setTimeout () function. Let’s use our debounce function.
edit: adding jsbin implementation
Lodash's debounce can do both. You'll have to specify whether it's leading or trailing.
https://lodash.com/docs#debounce
_.debounce(sendMail, 300, {
'leading': true,
'trailing': false
})
you can also write your own debounced function in just few lines jsbin example:
This will click first then debounce subsequent clicks.
function debounce(func, delay) {
console.log('debounce called with delay', delay);
var timer = 0;
return function debouncedFn() {
if (Date.now() - timer > delay) {
func();
}
timer = Date.now();
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With