How to delay the .keyup() handler until the user stops typing?

前端 未结 27 2602
半阙折子戏
半阙折子戏 2020-11-21 23:32

I’ve got a search field. Right now it searches for every keyup. So if someone types “Windows”, it will make a search with AJAX for every keyup: “W”, “Wi”, “Win”, “Wind”, “Wi

27条回答
  •  长发绾君心
    2020-11-21 23:58

    Saw this today a little late but just want to put this here in case someone else needed. just separate the function to make it reusable. the code below will wait 1/2 second after typing stop.

        var timeOutVar
    $(selector).on('keyup', function() {
    
                        clearTimeout(timeOutVar);
                        timeOutVar= setTimeout(function(){ console.log("Hello"); }, 500);
                    });
    

提交回复
热议问题