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

和自甴很熟 提交于 2019-12-23 11:35:15

问题


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',function() {

        reloadContent(); //execute load function

});

Any advice is appreciated


回答1:


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



回答2:


$('#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.



来源:https://stackoverflow.com/questions/6166213/how-to-delay-the-execution-of-a-javascript-function-after-a-live-keyup-event-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!