I am running a regular expression replace on an array (iterating through each index in the array), and pushing matches in to a new array. The code sometimes takes a second to execute, as the array it is running against is about 800 long.
I want to be able to run this code without having the browser lock up. I heard that there is some way to let the code execute without locking up the browser by using callback logic? I heard that this is similar to how Node is programmed.
Please could someone let me know how I would go about this?
My current code looks like this:
Code:
$("form[name=filefinder] input[name=s]").keyup( function(){
if(!s_cache[this.value]){
var regexp = new RegExp(this.value, "gi");
var list = files.split(/\n/g);
var result = [];
for(var i in list){
if(!!list[i].match(regexp)){
result.push(list[i].replace(regexp, "<span class=\"highlight\">"+this.value+"</span>"));
}
}
s_cache[this.value] = result;
}
update_filefinder_list(s_cache[this.value]);
});
as far as making it async, that's going to be somewhat complex. you have a solid object with lots of keys to iterate; there's no simple way to break the keys into groups and do them in batches, which is the typical async pattern.
i would focus on increasing app performance first.
if you search on every keyup(), you'll have a ton of hits for "e" and other single-letter chars as the phrase is typed.
better to only search when there are 3 or more letters to search for:
Code:
if(!s_cache[this.value] && this.value.length>2 ){
also, test() is ~250% faster than match(), and since you don't need the matches, you won't miss the different output:
Code:
if( regexp.test ( list[i] ) ){
finally, if you don't need the case-insensitive search, or you can toLowerCase() everything before the search, you can make it about 20X faster (than the 2.5X faster code) using "".split(strWhat).join(strRep) instead of "".replace(rxWhat, srtRep)...
those optimizations should remove the performance problems in real-world conditions that led you to seek a complex async answer.
Bookmarks