函数节流和函数防抖

概念

1
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时

看一个栗子:

1
2
3
4
5
6
7
8
9
10
11
12
// 未节流之前的代码

// 模拟ajax请求
function ajax(con){
console.log('ajax'+ con);
}

var inputTextA = document.getElementById('texta');

inputTextA.addEventListener('keyup', function(e){
ajax(e.target.value)
})

未节流的操作示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 进行节流操作
function ajax(content) {
console.log('ajax request ' + content)
}

function debounce(fun, delay) {
return function (args) {
let that = this
let _args = args
clearTimeout(fun.id)
fun.id = setTimeout(function () {
fun.call(that, _args)
}, delay)
}
}

let inputb = document.getElementById('testa')

let debounceAjax = debounce(ajax, 500)

inputb.addEventListener('keyup', function (e) {
debounceAjax(e.target.value)
})

节流之后的操作示例