Mojo.Function

Namespace Detail

Method Summary

  • Mojo.Function.debounce(onCall, onTimeout, delay, optionalWindow)

Method Detail

Mojo.Function.debounce(onCall, onTimeout, delay, optionalWindow)

This utility can be used to "debounce" multiple calls to a function, so that it will only be called once, or to perform some related function after a delay during which the primary function has not been called.

For example, window resize events often come in a series as the window is resized. It's helpful to have UI only update after the last one. Alternatively, when typing a filter for a filtered list, the widget should only re-query when the user has stopped typing.

debounce() returns a wrapped onCall function which can be called just like the original. The given onCall function will be called immediately, and the onTimeout function will be scheduled to be called after the specified delay. Any additional invocations of the wrapper during this delay period will reset the delay timer in addition to calling onCall. When things "settle down", then the timer will expire, and the onTimeout function will be called. Arguments passed to the onTimeout function are a copy of the ones from the most recent invocation of the wrapper.

Example Use

We use debounce() to implement a user-driven delay for clearing a search string when the user is typing. The idea is that if they type 'abc' quickly, then the search string is not cleared, and we'll search for abc... But then if there is a delay before they press 'd', then the search string is cleared and we'll only search for 'd'.

// this.clearSearchString() will be called 1 second after
// the most recent call to this.delayedClear().
this.delayedClear = Mojo.Function.debounce(undefined,
  this.clearSearchString.bind(this), 1, this.controller.window);

Parameters

  • {function} onCall - Function to call each time the wrapper is invoked. May be undefined.
  • {function} onTimeout - Function to call when the wrapper is invoked, after the delay expires.
  • {integer} delay - Time in seconds to wait for function invocations to "settle down".
  • {string} optionalWindow - Controls which window the delay timer runs in. Defaults to 'window'.