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

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

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

我该怎么做呢?


当前回答

我使用这个小函数也是出于同样的目的,在用户停止输入一段特定的时间后,或者在以高速率触发的事件中执行一个函数,比如resize:

function delay(callback, ms) { var timer = 0; return function() { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { callback.apply(context, args); }, ms || 0); }; } // Example usage: $('#input').keyup(delay(function (e) { console.log('Time elapsed!', this.value); }, 500)); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="input">Try it: <input id="input" type="text" placeholder="Type something here..."/> </label>

工作原理:

delay函数将返回一个内部处理单个计时器的包装函数,在每次执行时,计时器都会根据所提供的时间延迟重新启动,如果在此时间之前发生多次执行,计时器将重置并重新启动。

当计时器最终结束时,执行回调函数,传递原始上下文和参数(在本例中,是jQuery的事件对象和DOM元素)。

更新2019-05-16

我在现代环境中使用ES5和ES6特性重新实现了该功能:

function delay(fn, ms) {
  let timer = 0
  return function(...args) {
    clearTimeout(timer)
    timer = setTimeout(fn.bind(this, ...args), ms || 0)
  }
}

该实现包含一组测试。

对于更复杂的东西,看看jQuery Typewatch插件。

其他回答

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…"/>

Use

mytimeout = setTimeout( expression, timeout );

其中expression是要运行的脚本,timeout是在它运行之前等待的时间(以毫秒为单位)——这不会暂停脚本,而是简单地延迟该部分的执行,直到超时完成。

clearTimeout(mytimeout);

将重置/清除超时,这样它就不会在表达式中运行脚本(就像取消),只要它还没有被执行。

在ES6中,也可以使用箭头函数语法。

在本例中,在调用searchFunc发出查询请求之前,在用户完成输入之后,代码将keyup事件延迟400ms。

const searchbar = document.getElementById('searchBar');
const searchFunc = // any function

// wait ms (milliseconds) after user stops typing to execute func
const delayKeyUp = (() => {
    let timer = null;
    const delay = (func, ms) => {
        timer ? clearTimeout(timer): null
        timer = setTimeout(func, ms)
    }
    return delay
})();

searchbar.addEventListener('keyup', (e) => {
    const query = e.target.value;
    delayKeyUp(() => {searchFunc(query)}, 400);
})

更新后的Typescript版本:

const delayKeyUp = (() => {
  let timer: NodeJS.Timeout;
  return (func: Function, ms: number) => {
    timer ? clearTimeout(timer) : null;
    timer = setTimeout(() => func(), ms);
  };
})();

如果你想在类型完成后搜索,使用一个全局变量来保存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);  
}   

解释

使用变量存储超时函数。然后使用clearTimeout()清除该变量的任何活动超时函数,然后使用setTimeout()再次设置活动超时函数。我们首先运行clearTimeout(),因为如果用户键入“hello”,我们希望函数在用户按下“o”键后不久运行(而不是每个字母一次)。

演示工作

超级简单的方法,设计用于在用户在文本字段中输入完成后运行一个函数…

$(document).ready(function(e) { var timeout; var delay = 2000; // 2 seconds $('.text-input').keyup(function(e) { $('#status').html("User started typing!"); if(timeout) { clearTimeout(timeout); } timeout = setTimeout(function() { myFunction(); }, delay); }); function myFunction() { $('#status').html("Executing function for user!"); } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> Status: <span id="status">Default Status</span><br> <textarea name="text-input" class="text-input"></textarea>