https://css-tricks.com/debouncing-throttling-explained-examples/ pointed me to http://unscriptable.com/2009/03/20/debouncing-javascript-methods/.
If you are already using jQuery, underscore.js or Lodash you have versions of this in your framework. The simplest version not embedded in a library or framework which doesn’t use prototypes was:
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)
};
}
func is the function to call, threshold is the interval expressed in milliseconds and execAsap determines if the function is called at the beginning or end of the interval. The function will only be called once per interval.
document.onmousemove = debounce(function (e) {
/* do something here, but only once after mouse cursor stops */
}, 250, false);