听起来你想要underscore.js debounce 方法
基本上你会像这样使用它:(为简洁起见,使用 jQuery)
$('#searchfield').keyup(_.debounce(getSuggestions, 250));
getSuggestions
这将仅在事件未触发 250 毫秒时调用该函数。因此,如果您正在打字,在您暂停至少四分之一秒之前,什么都不会发生。
它的工作原理粘贴在下面。它围绕一个函数包装了一堆逻辑并返回一个新函数。函数式编程不是很有趣吗?
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
};