由于我误解了这个问题,这里有两个优化(两者可以一起使用):
缓存查询结果,只是偶尔定时更新
不是很漂亮,但考虑到性能提升至关重要,可能会提供一个强大的解决方案。
window.lastValue = null;
window.cachedElements = null;
window.updateCachedElements = function(){ cachedElements = $('.class'); };
function someFunction() {
cachedElements.each(function() {
var $this = $(this);
if ($this.text().match(lastValue)) {
$this.addClass('found');
} else {
$this.removeClass('found');
}
});
}
$('input[type=text]').keyup(function() {
if(cachedElements === null) {
updateCachedElements();
}
lastValue = $(this).val()
someFunction();
});
setInterval(function(){ updateCachedElements(); someFunction(); }, 500);
使用 debounce(一种节流形式)将someFunction 调用次数降至 1/100 毫秒或每秒 10 次
在someFunction 定义之后(和外部),执行:
someFunction = debounce(someFunction, 100);
来自underscore.js的去抖实现:
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = (Date.now || new Date().getTime()) - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};