在正式介绍underscore的debounce函数之前,我们先来复习一下几个小小的概念,请先看如下这个简单的示例,以便大家理解。
function a() {
var bv = 'B';
console.log('A');
function b() {
console.log(bv)
}
return b
};
var s = a();
s();
大家可以看到,先后输出了A,B。由此再来看我们的debounce方法,就会好理解很多。
贴上debounce源码网址点击打开链接
_.debounce = function(func, wait, immediate) {
var timeout, result;
var later = function(context, args) {
timeout = null;
if (args) result = func.apply(context, args); //func在当前环境中的上下文中执行
};
var debounced = restArguments(function(args) {
if (timeout) clearTimeout(timeout); //清除上一个timeout
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(this, args);
} else {
timeout = _.delay(later, wait, this, args);
}
return result;
});
debounced.cancel = function() {
clearTimeout(timeout);
timeout = null;
};
return debounced;
};
debounce方法的实际调用是将实际调用的方法转化为debounce入参对象,再不断调用的过程中,清除掉上一个延时执行的方法,来达到去抖的目的。
我们通常像这样调用debounce函数,var a = _(function(){xxxx}.debounce(200)),此时将一个方法以及延时计算的毫秒数值传入我们的debounce函数。