Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit or throttle the number of function calls (in order to increase performance) in this function call?

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?

like image 918
jcubic Avatar asked Feb 08 '23 19:02

jcubic


1 Answers

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);
});
like image 104
Rory McCrossan Avatar answered Feb 11 '23 00:02

Rory McCrossan