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

前端 未结 27 2986
半阙折子戏
半阙折子戏 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-22 00:04

    Combining CMS answer with Miguel's one yields a robust solution allowing concurrent delays.

    var delay = (function(){
        var timers = {};
        return function (callback, ms, label) {
            label = label || 'defaultTimer';
            clearTimeout(timers[label] || 0);
            timers[label] = setTimeout(callback, ms);
        };
    })();
    

    When you need to delay different actions independently, use the third argument.

    $('input.group1').keyup(function() {
        delay(function(){
            alert('Time elapsed!');
        }, 1000, 'firstAction');
    });
    
    $('input.group2').keyup(function() {
        delay(function(){
            alert('Time elapsed!');
        }, 1000, '2ndAction');
    });
    

提交回复
热议问题