StackOverflow 中标签的 AutoSuggest 功能如何避免每次击键时进行查询

发布于 2024-08-10 11:42:21 字数 202 浏览 10 评论 0原文

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

如果有人能解释我如何通过不在每个 keyup 上运行查询来实现 stackOverflow 所做的事情,那就太棒了。

I am trying to implement a similar feature like the autosuggest feature for tags available below the text area on this site using Jquery. I am trying to figure out how the requests are sent after a few keystrokes and not after every keystroke. I am using a 'keyup' event to trigger the request on my app. I was made to realize that this may result in too many server hits and may affect performance.

It would be awesome if some could explain how i could implement the kind of thing stackOverflow does by not having a query run on every keyup.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

话少心凉 2024-08-17 11:42:21

我的一个 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 经验,但是来自

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

var timer;
    function chk_me(){

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

I have a similar feature in one of my windows applications. When the user types a character, a timer is started with a 1 second interval. In the Tick event, the search is started. If the user types again, the timer is restarted. So the search is only performed if the keyboard has been idle for more than a second.

Short sample (it's in C#, but easy enough to follow):

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();
    }
}

I'm not experienced in Javascript, but the anwswer from here will help you I think:

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

var timer;
    function chk_me(){

       clearTimeout(timer);
       timer=setTimeout(function validate(){...},1000);
    }
愿得七秒忆 2024-08-17 11:42:21
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;
        }
    };
}
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;
        }
    };
}
风渺 2024-08-17 11:42:21

您所指的方法称为“Debounce”

我通常在所有脚本的底部都有一个“Debounce”函数

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); 
    }; 
};

然后每当我做任何可以从 debounce 中受益的事情时我都可以通用地使用它

所以您的代码将被编写为

$("#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 风格 AJAX 搜索 了解类似的用例...

the method you are referring to is called "Debouncing"

I usually have a "Debounce" function at the bottom of all my scripts

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); 
    }; 
};

And then whenever I do anything that will benefit from a debounce I can use it generically

So your code would be written as

$("#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*/
));

see Facebook Style AJAX Search for a similar usecase...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文