|
Underscore has a nifty function, _.debounce, which given a function f, returns a version of the function that behaves as the one in your interview question. http://underscorejs.org/#debounce Even if not using libraries, it would be nice to abstract that into its own function when you inevitably want to use it again in some other control. The code is pretty simple - very similar to what you did: function (func, wait, immediate) {
var timeout, args, context, timestamp, result;
return function() {
context = this;
args = arguments;
timestamp = new Date();
var later = function() {
var last = (new Date()) - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) result = func.apply(context, args);
return result;
};
}
|