我有一个使用 javascript 的自定义自动完成功能,它调用下面的 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 数据不是静态数据集。网络服务根据我输入的字符进行搜索。所以我无法在客户端缓存数据。所以我无能为力。
var timeout; // scope global
if (timeout != "")
{
clearTimeout(timeout);
}
timeout = setTimeout(function(){
//Code to retrieve suggestions
},50);
最佳答案
您可以使用 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
}
})();
请注意,此版本仅在距离小于 300ms 的距离内按下多个按键时,才会在按下最后一个按键时调用 ACCrequestSuggestions
。这可能会导致问题,但通常只会向用户显示一个结果,这当然应该是最后一次按键生成的结果。
关于javascript自动完成性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25260874/