开发者

How to delay the Execution of a Javascript Function After a Live Keyup event is called?

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

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.

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',funct开发者_StackOverflow社区ion() {

        reloadContent(); //execute load function

});

Any advice is appreciated


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


$('#searchinput').live('keyup',function() {
    window.setTimeout(function(){
        reloadContent(); //execute load function
    },1000);
});

This will make a delay, but I think you need not only delay to make what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜