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

前端 未结 27 2550
半阙折子戏
半阙折子戏 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:02

    Use

    mytimeout = setTimeout( expression, timeout );
    

    where expression is the script to run and timeout is the time to wait in milliseconds before it runs - this does NOT hault the script, but simply delays execution of that part until the timeout is done.

    clearTimeout(mytimeout);
    

    will reset/clear the timeout so it does not run the script in expression (like a cancel) as long as it has not yet been executed.

    0 讨论(0)
  • 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');
    });
    
    0 讨论(0)
  • 2020-11-22 00:07

    You could also look at underscore.js, which provides utility methods like debounce:

    var lazyLayout = _.debounce(calculateLayout, 300);
    $(window).resize(lazyLayout);
    
    0 讨论(0)
  • 2020-11-22 00:07

    Delay Multi Function Calls using Labels

    This is the solution i work with. It will delay the execution on ANY function you want. It can be the keydown search query, maybe the quick click on previous or next buttons ( that would otherwise send multiple request if quickly clicked continuously , and be not used after all). This uses a global object that stores each execution time, and compares it with the most current request.

    So the result is that only that last click / action will actually be called, because those requests are stored in a queue, that after the X milliseconds is called if no other request with the same label exists in the queue!

    function delay_method(label,callback,time){
        if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}  
        delayed_methods[label]=Date.now();
        var t=delayed_methods[label];
        setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{  delayed_methods[label]=""; callback();}}, time||500);
      }
    

    You can set your own delay time ( its optional, defaults to 500ms). And send your function arguments in a "closure fashion".

    For example if you want to call the bellow function:

    function send_ajax(id){console.log(id);}
    

    To prevent multiple send_ajax requests, you delay them using:

    delay_method( "check date", function(){ send_ajax(2); } ,600);

    Every request that uses the label "check date" will only be triggered if no other request is made in the 600 miliseconds timeframe. This argument is optional

    Label independency (calling the same target function) but run both:

    delay_method("check date parallel", function(){send_ajax(2);});
    delay_method("check date", function(){send_ajax(2);});
    

    Results in calling the same function but delay them independently because of their labels being different

    0 讨论(0)
  • 2020-11-22 00:08

    If someone like to delay the same function, and without external variable he can use the next script:

    function MyFunction() {
    
        //Delaying the function execute
        if (this.timer) {
            window.clearTimeout(this.timer);
        }
        this.timer = window.setTimeout(function() {
    
            //Execute the function code here...
    
        }, 500);
    }
    
    0 讨论(0)
  • 2020-11-22 00:08

    Take a look at the autocomplete plugin. I know that it allows you to specify a delay or a minimum number of characters. Even if you don't end up using the plugin, looking through the code will give you some ideas on how to implement it yourself.

    0 讨论(0)
提交回复
热议问题