如何在调用Live Keyup事件后延迟执行Javascript函数? [英] How to delay the Execution of a Javascript Function After a Live Keyup event is called?

查看:75
本文介绍了如何在调用Live Keyup事件后延迟执行Javascript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿程序员,我已从我的下面的函数中删除了所有内容,只是准确定位了我需要的帮助......

Hey programmers, I have removed everything from my function below to just target exactly what I need help with...

调用keyup事件后,reloadContent函数将进行ajax调用以从数据库中收集新数据。

After the keyup event is called, the reloadContent function will make an ajax call to gather new data from a database.

唯一的问题是,我的服务器正在超载,因为每次键入后键盘事件都没有延迟该函数被调用。

Only problem is, my servers are overloading because there is no delay from the keyup events, after every keyup the function is called.

在调用reloadContent函数之前,我需要一种方法来延迟,比如1秒。这样它就不会运行4次(当用户键入john时),但只有1次用户键入(john),假设他们可以输入超过1个字符/秒。

I need a way to delay, say 1 second, before the reloadContent function is called. This way it will not run 4 times (when the user types in j o h n) but only 1 time after the user types (john), assuming they can type more than 1 character/sec.

$('#searchinput').live('keyup',function() {

        reloadContent(); //execute load function

});

任何建议表示赞赏

推荐答案

您可以在 keyup 处理程序中设置超时,并使用jQuery的 data()工具将其id与元素相关联。这样,如果在延迟用完之前再次触发 keyup 事件,您可以清除现有的超时并安排新的超时:

You can set a timeout in your keyup handler and use jQuery's data() facility to associate its id with the element. That way, if the keyup event is triggered again before the delay runs out, you can clear the existing timeout and schedule a new one:

$("#searchinput").live("keyup", function() {
    var $this = $(this);
    var timerId = $this.data("timerId");
    if (timerId) {
        window.clearTimeout(timerId);
    }
    $this.data("timerId", window.setTimeout(reloadContent, 1000));
});

这篇关于如何在调用Live Keyup事件后延迟执行Javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆