为了区分这两个思想,最常用的例子就是电梯例子,我们也通过该例子来比较两个思想。当有很多人用电梯时,我们不能每来一个人,电梯都特意去送这个人一趟。这样,电梯的运行方式可以有两种优化思想
debouncing
每上一个人,从这个人开始,指定时间(比如400ms)后电梯关闭开始送人。在程序中,也就是每发生一个事件,从这个事件往后T秒,执行回调函数。
//实现函数:
var debounce = function(func, delay) {
var inDebounce = undefined;
return function() {
debugger
var context = this,
args = arguments;
clearTimeout(inDebounce);
return inDebounce = setTimeout(function() {
return func.apply(context, args);
}, delay);
}
}
<!-- 调用函数 -->
<body>
<button >click me</button>
</body>
<script>
function aFunction(msg){
console.log(msg);
}
$('button').click(debounce(function() {
return aFunction('i am message');
}, 400));
</script>
Throttling
从上第一个人开始,电梯指定时间循环着执行,无论中间是否上人,都是每t秒运行一次。
//实现函数:
var throttle = function(func, limit) {
var inThrottle = undefined;
return function() {
var args = arguments,
context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
return setTimeout(function() {
return inThrottle = false;
}, limit);
}
};
};
<!-- 调用函数 -->
<body>
<button >click me</button>
</body>
<script>
function aFunction(msg){
console.log(msg);
}
$('button').click(throttle(function() {
return aFunction('i am message');
}, 400));
</script>