javascript自动完成性能问题

塞子

我有一个使用javascript的自定义自动完成功能,该功能在keyup函数下面调用,而keyup函数依次调用一个Web服务以获取结果。它会产生结果,但是当我在该字段中快速键入字符时,将逐渐为每个字符逐步细化结果,因此UI的最终感觉似乎很慢,是否有任何方法可以设置键入延迟,因此当用户在字段中输入大量的停顿时,将调用ACCrequestSuggestions函数来调用服务。还是有其他更好的方法使用jvascript处理此问题。请帮忙。

/**
* Handles keyup events.
*/
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {
var iKeyCode = oEvent.keyCode;
//for backspace (8) and delete (46), shows suggestions without typeahead
if (iKeyCode == 8 || iKeyCode == 46) {
    ACCrequestSuggestions(this, false);

//make sure not to interfere with non-character keys
} else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
    //ignore
} else {
    //request suggestions from the suggestion provider with typeahead
ACCrequestSuggestions(this,true);
        }
};

/**
* Generate results and create the autocomplete drop down
*/

ACCrequestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
                    bTypeAhead /*:boolean*/) {

var aSuggestions = [];

// suggestions function will invoke service call to generate results based on input
aSuggestions = new Suggestions();

   //provide suggestions to the control by building div of results
oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
};

更新 :

我按照建议使用了settimeout,效果很好。输入时感觉更快。我的websetvice数据不是静态数据集。Web服务根据我输入的字符进行搜索。所以我不能在客户端缓存数据。所以我无能为力。

var timeout; // scope global
if (timeout != "")
{
clearTimeout(timeout);
}
timeout = setTimeout(function(){
//Code to retrieve suggestions
},50);
chm-software.com

您可以使用setTimeout()创建延迟,并ACCrequestSuggestions在注册了多个击键之后仅调用一次:

AutoSuggestControl.prototype.handleKeyUp = (function() {
   var timer;
   return function (oEvent) {
     var that = this;
     try {
       clearTimeout(timer); //stop timeout on key up if it's already running
     } catch(ignore) {}
     //call your code with a given delay
     timer = setTimeout(function() {

       /***your original code***/
       var iKeyCode = oEvent.keyCode;
       //for backspace (8) and delete (46), shows suggestions without typeahead
       if (iKeyCode == 8 || iKeyCode == 46) {
         ACCrequestSuggestions(that, false);
       //make sure not to interfere with non-character keys
       } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
         //ignore
       } else {
         //request suggestions from the suggestion provider with typeahead
         ACCrequestSuggestions(that,true);
       }

     }, 300); //300 ms should be nice for performance and also for user experience
   }
})();

请标记为该版本仅ACCrequestSuggestions在敲击距离小于300毫秒的多个键时才按下最后一个键进行调用这可能会引起问题,但是通常只会向用户显示一个结果,并且当然应该是最后一次按键产生的结果。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章