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


i have function this:

function somefunction(text) {     $('.class').each(function() {         var $this = $(this);         if ($this.text().match(text)) {            $this.addclass('found');         } else {            $this.removeclass('found');         }     }); } 

and function executed in keyup event,

$('input[type=text]').keyup(function() {    somefunction($(this).val()); }); 

on ie if there lot of .class elements can slow, thought speed things if stop executing each call if function have been executed again before each finished. how can this?

you speed adding slight delay keyup handler dom affected after typing has ended instead of on each keystroke. can use :contains selector find 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, mentioned @a.wolff cache .class selector, work if no .class elements dynamically added 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); }); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -