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

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

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

我该怎么做呢?


当前回答

使用jQuery插件bindWithDelay:

element.bindWithDelay(eventType, [ eventData ], handler(eventObject), timeout, throttle)

其他回答

将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');
});

用户lodash javascript库并使用_.debounce函数

changeName: _.debounce(function (val) {
  console.log(val)                
}, 1000)

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

如果你想在类型完成后搜索,使用一个全局变量来保存setTimout调用返回的超时,如果它还没有发生,就用clearTimeout取消它,这样它就不会触发超时,除非在最后一个keyup事件

var globalTimeout = null;  
$('#id').keyup(function(){
  if(globalTimeout != null) clearTimeout(globalTimeout);  
  globalTimeout =setTimeout(SearchFunc,200);  
}   
function SearchFunc(){  
  globalTimeout = null;  
  //ajax code
}

或者使用匿名函数:

var globalTimeout = null;  
$('#id').keyup(function() {
  if (globalTimeout != null) {
    clearTimeout(globalTimeout);
  }
  globalTimeout = setTimeout(function() {
    globalTimeout = null;  

    //ajax code

  }, 200);  
}   

如果有人喜欢延迟相同的函数,并且没有外部变量,他可以使用下一个脚本:

function MyFunction() {

    //Delaying the function execute
    if (this.timer) {
        window.clearTimeout(this.timer);
    }
    this.timer = window.setTimeout(function() {

        //Execute the function code here...

    }, 500);
}