我有一个搜索域。现在它会搜索每一个按键。所以如果有人输入“Windows”,它会用AJAX搜索每个键:“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”。
我想有一个延迟,所以它只在用户停止输入200毫秒时搜索。
在keyup函数中没有这个选项,我尝试了setTimeout,但它不起作用。
我该怎么做呢?
我有一个搜索域。现在它会搜索每一个按键。所以如果有人输入“Windows”,它会用AJAX搜索每个键:“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”。
我想有一个延迟,所以它只在用户停止输入200毫秒时搜索。
在keyup函数中没有这个选项,我尝试了setTimeout,但它不起作用。
我该怎么做呢?
当前回答
将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');
});
其他回答
根据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)变量与输入不匹配
Use
mytimeout = setTimeout( expression, timeout );
其中expression是要运行的脚本,timeout是在它运行之前等待的时间(以毫秒为单位)——这不会暂停脚本,而是简单地延迟该部分的执行,直到超时完成。
clearTimeout(mytimeout);
将重置/清除超时,这样它就不会在表达式中运行脚本(就像取消),只要它还没有被执行。
var globalTimeout = null;
$('#search').keyup(function(){
if(globalTimeout != null) clearTimeout(globalTimeout);
globalTimeout =setTimeout(SearchFunc,200);
});
function SearchFunc(){
globalTimeout = null;
console.log('Search: '+$('#search').val());
//ajax code
};
这对我来说很有效,我延迟了搜索逻辑操作,并检查值是否与文本字段中输入的值相同。如果值相同,则继续执行与搜索值相关的数据的操作。
$('#searchText').on('keyup',function () {
var searchValue = $(this).val();
setTimeout(function(){
if(searchValue == $('#searchText').val() && searchValue != null && searchValue != "") {
// logic to fetch data based on searchValue
}
else if(searchValue == ''){
// logic to load all the data
}
},300);
});
如果你想在一段时间后做一些事情,并在特定的事件(如keyup)后重置定时器,最好的解决方案是使用clearTimeout和setTimeout方法:
// declare the timeout variable out of the event listener or in the global scope
var timeout = null;
$(".some-class-or-selector-to-bind-event").keyup(function() {
clearTimeout(timout); // this will clear the recursive unneccessary calls
timeout = setTimeout(() => {
// do something: send an ajax or call a function here
}, 2000);
// wait two seconds
});