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

前端 未结 27 2629
半阙折子戏
半阙折子戏 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条回答
  •  梦毁少年i
    2020-11-22 00:21

    Another slight enhancement on CMS's answer. To easily allow for separate delays, you can use the following:

    function makeDelay(ms) {
        var timer = 0;
        return function(callback){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
        };
    };
    

    If you want to reuse the same delay, just do

    var delay = makeDelay(250);
    $(selector1).on('keyup', function() {delay(someCallback);});
    $(selector2).on('keyup', function() {delay(someCallback);});
    

    If you want separate delays, you can do

    $(selector1).on('keyup', function() {makeDelay(250)(someCallback);});
    $(selector2).on('keyup', function() {makeDelay(250)(someCallback);});
    

提交回复
热议问题