有时候我们不希望回调函数被频繁调用,列如输入框键盘落下操作后,发送ajax
<input type="text" class="down" placeholder="输入框">
<script src="../jquery-1.11.1.min.js"></script>
<script>
// $('.down').on('keydown', fn); // 每次键盘落下都会调用
$('.down').on('keydown', debounce(callBack, 2500)); // 延迟2.5s才会调用,而且如果上次回调还未执行,再次键盘操作,重新计时
function callBack(e) {
var _$this = $(e.target);
console.log(_$this.val());
console.log(this);
}
function debounce(fn, delay) {
var timer = null; // 声明定时器
return function () {
var _this = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(_this, args); // 由于setTimeout里面的this指针统一指向winodw,所以使用apply,将指针重新指向调用函数的地方(dom容器),在这个案例就是Input输入框
}, delay);
}
}