函数节流与去抖

### Debounce
The Debounce technique allow us to “group” multiple sequential calls in a single one.
Resize,keypress on autocomplete form with Ajax request

### Throttle
By using _.throttle, we don’t allow to our function to execute more than once every X milliseconds.

The main difference between this and debouncing is that throttle guarantees the execution of the function regularly, at least every X milliseconds.

Infinite scrolling

### requestAnimationFrame (rAF)

### Conclusion
debounce: Grouping a sudden burst of events (like keystrokes) into a single one.
throttle: Guaranteeing a constant flow of executions every X milliseconds. Like checking every 200ms your scroll position to trigger a CSS animation.
requestAnimationFrame: a throttle alternative. When your function recalculates and renders elements on screen and you want to guarantee smooth changes or animations. Note: no IE9 support.

实现

节流:间隔一定时间触发回调来控制函数调用频率
拖拽功能,射击游戏,计算鼠标移动的距离,Canvas 模拟画板功能,搜索联想

监听滚动事件判断是否到页面底部自动加载更多:
给 scroll 加了 debounce 后,只有用户停止滚动后,才会判断是否到了页面底部;
如果是 throttle 的话,只要页面滚动就会间隔一段时间判断一次

去抖:对于连续的事件响应我们只需要执行一次回调
resize/scroll 触发统计事件,文本输入的验证, $PS: 搜索联想应该在这里

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function debounce(fn, wait) {
var timer = null;
return function () {
var context = this
var args = arguments
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function () {
fn.apply(context, args)
}, wait)
}
}
function throttle(fn, wait) {
var previous = 0
var timer = null
return function () {
var context = this
var args = arguments
if (!previous) {
previous = Date.now()
fn.apply(context, args)
} else if (previous + wait >= Date.now()) {
if (timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(function () {
previous = Date.now()
fn.apply(context, args)
}, wait)
} else {
previous = Date.now()
fn.apply(context, args)
}
}
}

17:00

knowledge is no pay,reward is kindness
0%