Debouncing a Function


Given a function f, and N return a debounced f of N milliseconds.

That is, as long as the debounced f continues to be invoked, f itself will not be called for N milliseconds.

Understanding the Problem

A debounce function is a wrapper function that delays the invocation of another function. Subsequent invocations extends the delay. 

Optionally, the wrapped function may accept parameters. Each unique set of parameters need to be de-bounced separately

Solving it

Most languages support a delayed execution of a function either through callbacks or via concurrency libraries. 

return function() {
    executeDelay( N , function() { f(); } )
}

The challenge is to expand the logic above, so that 
  • Each de-bounced invocation extends the delay, and
  • Parameters to each function are tracked
One approach, is to keep track of each delayed function and the parameters in a HashMap. 

The de-bounced function is responsible for scheduling the delayed task and adding it to the map. If the task already exists the delay is increased. 

The delayed task is responsible for re-scheduling it's execution based on the delay pending.

Code

The following links to a code posted in a StackOverflow question that describes a solution in Java utilizing a ScheduledExecutorService and a ConcurrentHashMap