As I misunderstood the question, here're two optimizations instead (both can be used together):
Cache the query result, only occasionally updating it by timer
Not really beautiful but may provide a robust solution given that the performance gain is critical.
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);
Use debounce (a form of throttling) to minimize number of someFunction
calls to 1/100ms or 10 per second
After (and outside) the someFunction
definition, do:
someFunction = debounce(someFunction, 100);
Debounce implementation from 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;
};
};