我有一个搜索域。现在它会搜索每一个按键。所以如果有人输入“Windows”,它会用AJAX搜索每个键:“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”。
我想有一个延迟,所以它只在用户停止输入200毫秒时搜索。
在keyup函数中没有这个选项,我尝试了setTimeout,但它不起作用。
我该怎么做呢?
我有一个搜索域。现在它会搜索每一个按键。所以如果有人输入“Windows”,它会用AJAX搜索每个键:“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”。
我想有一个延迟,所以它只在用户停止输入200毫秒时搜索。
在keyup函数中没有这个选项,我尝试了setTimeout,但它不起作用。
我该怎么做呢?
当前回答
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
};
其他回答
根据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);
将重置/清除超时,这样它就不会在表达式中运行脚本(就像取消),只要它还没有被执行。
用户lodash javascript库并使用_.debounce函数
changeName: _.debounce(function (val) {
console.log(val)
}, 1000)
将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);
}