StackOverflow中标记的AutoSuggest功能如何避免在每个键击中查询

时间:2009-11-06 17:01:15

标签: jquery autocomplete autosuggest

我正在尝试使用Jquery为本网站文本区域下方的标签实现类似自动提示功能的类似功能。我试图弄清楚在几次击键后如何发送请求,而不是在每次击键后发送。我正在使用'keyup'事件来触发我的应用程序上的请求。我意识到这可能会导致服务器命中次数过多,并可能影响性能。

如果有人可以通过不在每个keyup上运行查询来解释我如何实现stackOverflow所做的事情,那将是非常棒的。

3 个答案:

答案 0 :(得分:6)

我的一个Windows应用程序中有类似的功能。当用户键入字符时,以1秒的间隔启动计时器。在Tick事件中,搜索开始。如果用户再次键入,则重新启动计时器。因此,仅在键盘空闲超过一秒钟时才执行搜索。

简短的样本(它在C#中,但很容易遵循):

public partial class Form1 : Form
{
    private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

    public Form1()
    {
        InitializeComponent();

        timer.Interval = 1000;
        timer.Tick += new EventHandler(timer_Tick);
    }

    void timer_Tick(object sender, EventArgs e)
    {
        timer.Stop();

        // Do search, or what ever you want to do
        Console.WriteLine("Searching...");
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (timer.Enabled)
        {
            timer.Stop();
        }

        timer.Start();
    }
}

我没有Javascript的经验,但here的anwswer会帮助你,我想:

<input name="domain" type="text" id="domain" onKeyUp="javascript:chk_me();">

var timer;
    function chk_me(){

       clearTimeout(timer);
       timer=setTimeout(function validate(){...},1000);
    }

答案 1 :(得分:2)

var activity = new ActivityTimer(1000, function() {
    doSearch();
});

$("#searchBox").keyup(function(){ activity.reset() });

function ActivityTimer(deadline, callback) {
    var timer = -1;

    this.reset = function() {
        this.cancel();
        timer = setTimeout(callback, deadline);
    };

    this.cancel = function() {
        if(timer >= 0) {
            clearTimeout(timer);
            timer = -1;
        }
    };
}

答案 2 :(得分:2)

您指的方法称为“Debouncing”

我的所有脚本底部通常都有一个“去抖动”功能

var debounce=function(func, threshold, execAsap) {
    var timeout;
    return function debounced () {
        var obj = this, args = arguments;
        function delayed () {
            if (!execAsap)
                func.apply(obj, args);
            timeout = null; 
        };
        if (timeout)
            clearTimeout(timeout);
        else if (execAsap)
            func.apply(obj, args);
        timeout = setTimeout(delayed, threshold || 100); 
    }; 
};

然后每当我做任何可以从去抖中受益的事情时,我都可以使用它

所以你的代码将被写为

$("#search_box").keyup(debounce(function() {
    //do stuff in this function  
}
,350 /*determines the delay in ms*/
,false /*should it execute on first keyup event, 
       or delay the first event until 
       the value in ms specified above*/
));

请参阅Facebook Style AJAX Search了解类似的用例......