防止回调执行直到输入停止 [英] Preventing a callback from executing until input stops
问题描述
如果没有按下任何键,则触发 AJAX 调用的计时器.如果按下某个键,则中止最后一个计时器并添加一个新计时器.这就是我想做但未能成功的事情.这是我的代码:
A timer to fire an AJAX call if no key is pressed. If a key is pressed, then abort the last timer and add a new timer. That is what I want to do but failed to success. Here is my code:
var t;
input.onkeyup = function(){
$('.confirmText').html('Checking...');
var timeStampObj = new Date()
var timeStamp = timeStampObj.getTime();
var oldTimeStamp = $(this).attr('timeStamp');//I store a timeStamp in the element
if(timeStamp < 500 + oldTimeStamp){
$(this).attr('timeStamp', timeStamp);
clearTimeout(t);
}
t = setTimeout(function(){
$.ajax({
url: 'serverScripts/settings/checkEmailAvailability.php',
data: 'email='+email,
success: function(text){
if(text == 'available'){
$('.confirmText').html('Available!');
}else{
$('.confirmText').html('Occupied!');
}
}
});
}, 500);//Half a second
$(this).attr('timeStamp', timeStamp);
}
推荐答案
听起来您需要一个去抖动器.术语来自电子产品.这是一种防止在某个时间阈值内触发多个事件的方法.您可以使用以下函数创建一个新函数,该函数仅在自上次事件以来经过给定时间后才会被调用.
It sounds like you're asking for a debouncer. The term comes from electronics. It's a way to prevent multiple events from firing within some time threshold. You can use the following function to create a new function that will only be called if a given amount of time has passed since the last event.
function debounce(callback, timeout, _this) {
var timer;
return function(e) {
var _that = this;
if (timer)
clearTimeout(timer);
timer = setTimeout(function() {
callback.call(_this || _that, e);
}, timeout);
}
}
// requires jQuery
$("div").click(debounce(function() {
console.log("tset");
}, 2000));
只要点击事件持续触发,给 debounce
的回调就不会执行.
The callback given to debounce
won't execute as long as click events keep firing.
优秀的 Underscore.js 库包括 一个等效的函数,并且至少有几个 jQuery 插件:
The excellent Underscore.js library includes an equivalent function and there are at least a couple jQuery plugins:
- http://code.google.com/p/jquery-debounce/
- http://benalman.com/code/projects/jquery-dotimeout/examples/debounce/
这篇关于防止回调执行直到输入停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!