I have a function that look like this:
function someFunction(text) {
$('.class').each(function() {
var $this = $(this);
if ($this.text().match(text)) {
$this.addClass('found');
} else {
$this.removeClass('found');
}
});
}
and that function is executed in keyup event,
$('input[type=text]').keyup(function() {
someFunction($(this).val());
});
on IE if there are lot of .class
elements it can be slow, I thought that I could speed things up if I stop executing the each call if the function have been executed again before each is finished. How can I do this?
You could speed this up by adding a slight delay to the keyup
handler so that the DOM is only affected after typing has ended instead of on each keystroke. You can also use the :contains
selector to find the elements. Try this:
function someFunction(text) {
$('.class').removeClass('found').filter(':contains("' + text + '")').addClass('found');
}
var timer;
$('input[type=text]').keyup(function() {
clearTimeout(timer);
timer = setTimeout(function() {
someFunction(this.value);
}, 100);
});
Also, as mentioned by @A.Wolff you could cache the .class
selector, but this would only work if no .class
elements are dynamically added to the DOM while you're searching:
var $elements = $('.class');
function someFunction(text) {
$elements.removeClass('found').filter(':contains("' + text + '")').addClass('found');
}
var timer;
$('input[type=text]').keyup(function() {
clearTimeout(timer);
timer = setTimeout(function() {
someFunction(this.value);
}, 100);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With