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

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

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

我该怎么做呢?


当前回答

使用标签延迟多函数调用

这是我的解决方案。它会延迟你想要的任何函数的执行。它可以是按下键搜索查询,也可以是快速单击上一个或下一个按钮(否则如果连续快速单击将发送多个请求,并且最终不会使用)。它使用一个全局对象存储每次执行时间,并将其与最新的请求进行比较。

因此,结果是只有最后一个点击/动作将被实际调用,因为这些请求存储在队列中,如果队列中没有其他具有相同标签的请求,则在X毫秒后调用!

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

您可以设置自己的延迟时间(可选,默认为500ms)。并以“闭包方式”发送函数参数。

例如,如果你想调用下面的函数:

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

为了防止多个send_ajax请求,可以使用以下方法延迟它们:

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

每个使用标签“check date”的请求只有在600毫秒的时间范围内没有其他请求时才会被触发。这个参数是可选的

标签独立性(调用相同的目标函数),但同时运行:

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

导致调用相同的函数,但由于它们的标签不同而单独延迟它们

其他回答

好吧,我也做了一段代码限制高频ajax请求由Keyup / Keydown。看看这个:

https://github.com/raincious/jQueue

像这样提问:

var q = new jQueue(function(type, name, callback) {
    return $.post("/api/account/user_existed/", {Method: type, Value: name}).done(callback);
}, 'Flush', 1500); // Make sure use Flush mode.

并像这样绑定事件:

$('#field-username').keyup(function() {
    q.run('Username', this.val(), function() { /* calling back */ });
});
// 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);
}

我很惊讶,没有人提到多重输入的问题在CMS的非常好的剪辑。

基本上,你必须为每个输入分别定义延迟变量。否则,如果有人把文本放在第一个输入,并迅速跳转到其他输入并开始输入,第一个的回调将不会被调用!

下面是我根据其他答案编写的代码:

(function($) {
    /**
     * KeyUp with delay event setup
     * 
     * @link http://stackoverflow.com/questions/1909441/jquery-keyup-delay#answer-12581187
     * @param function callback
     * @param int ms
     */
    $.fn.delayKeyup = function(callback, ms){
            $(this).keyup(function( event ){
                var srcEl = event.currentTarget;
                if( srcEl.delayTimer )
                    clearTimeout (srcEl.delayTimer );
                srcEl.delayTimer = setTimeout(function(){ callback( $(srcEl) ); }, ms);
            });

        return $(this);
    };
})(jQuery);

该解决方案将setTimeout引用保留在输入的delayTimer变量中。它还像fazzyx建议的那样将元素的引用传递给回调。

在IE6, 8(comp - 7), 8和Opera 12.11中测试。

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

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

function MyFunction() {

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

        //Execute the function code here...

    }, 500);
}