我有一个搜索域。现在它会搜索每一个按键。所以如果有人输入“Windows”,它会用AJAX搜索每个键:“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”。

我想有一个延迟,所以它只在用户停止输入200毫秒时搜索。

在keyup函数中没有这个选项,我尝试了setTimeout,但它不起作用。

我该怎么做呢?


当前回答

根据CMS的回答,我做出了这样的决定:

把下面的代码包括jQuery后:

/*
 * delayKeyup
 * http://code.azerti.net/javascript/jquery/delaykeyup.htm
 * Inspired by CMS in this post : http://stackoverflow.com/questions/1909441/jquery-keyup-delay
 * Written by Gaten
 * Exemple : $("#input").delayKeyup(function(){ alert("5 secondes passed from the last event keyup."); }, 5000);
 */
(function ($) {
    $.fn.delayKeyup = function(callback, ms){
        var timer = 0;
        $(this).keyup(function(){                   
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
        });
        return $(this);
    };
})(jQuery);

简单地像这样使用:

$('#input').delayKeyup(function(){ alert("5 secondes passed from the last event keyup."); }, 5000);

注意:作为参数传递的函数中的$(this)变量与输入不匹配

其他回答

看一下autocomplete插件。我知道它允许您指定延迟或最小字符数。即使你最终没有使用这个插件,浏览代码也会给你一些关于如何自己实现它的想法。

将CMS的答案与Miguel的答案相结合,产生了允许并发延迟的健壮解决方案。

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

当您需要单独延迟不同的操作时,请使用第三个参数。

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

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

今天看到这个有点晚,但我想把它放在这里,以防有人需要。只需将函数分离以使其可重用。下面的代码在输入stop后将等待1/2秒。

    var timeOutVar
$(selector).on('keyup', function() {

                    clearTimeout(timeOutVar);
                    timeOutVar= setTimeout(function(){ console.log("Hello"); }, 500);
                });
// Get an global variable isApiCallingInProgress

//  check isApiCallingInProgress 
if (!isApiCallingInProgress) {
// set it to isApiCallingInProgress true
      isApiCallingInProgress = true;

      // set timeout
      setTimeout(() => {
         // Api call will go here

        // then set variable again as false
        isApiCallingInProgress = false;     
      }, 1000);
}

jQuery:

变量超时 = 空; $('#input').keyup(function() { 清除超时(超时); 超时 = 设置超时(() => { console.log($(this).val()); }, 1000); }); <script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js”></script> <输入类型=“文本” id=“输入” 占位符=“在此处键入...”/>

纯Javascript:

let input = document.getElementById('input'); 让timeout = null; 输入。addEventListener('keyup',函数(e) { clearTimeout(超时); timeout = setTimeout(函数(){ console.log(价值:,input.value); }, 1000); }); <input type="text" id="input" placeholder=" type here…"/>