let inputa = document.getElementById(‘unDebounce’)
inputa.addEventListener(‘keyup’, function (e) {
ajax(e.target.value)
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
向input框中一直输入文字:
只要按下键盘,就会触发ajax请求。这样会增加很多无效的请求浪费资源,实际应用中,是等用户输出完整的字符后才会请求。下面优化一下:
//模拟一段ajax请求
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(‘debounce’)
let debounceAjax = debounce(ajax, 500)
inputb.addEventListener(‘keyup’, function (e) {
debounceAjax(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
- 24
优化后减少不必要的请求:
这里加入了防抖以后,当频繁的输入时,并不会发送请求,只有在指定间隔内没有输入时,才会执行函数。如果停止输入但是在指定间隔内又输入,会重新触发计时。
或者 debounce函数 这么写也行:主要是需要一个id来标识之前的函数
function debounce(fun, delay) {
let fun_id;
return function (args) {
let _args = args;
let that = this;
clearTimeout(fun_id);
fun_id = setTimeout(function () {
fun.call(that, _args);
}, delay)
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
函数节流(throttle)
概念:规定在给定时间内,只能触发一次函数。如果在给定时间内触发多次函数,只有一次生效。
栗子:
//模拟一段ajax请求
function ajax(content) {
console.log('ajax request ' + content)
}
function throttle(fun, delay) {
let last;
return function (args) {
let that = this;
let _args = args;
let now = +new Date();
if (last && last + delay > now) {
clearTimeout(fun.id);
fun.id = setTimeout(function () {
last = now;
fun.call(that, _args);
}, delay);
} else {
last = now;
fun.call(that, _args);
}
}
}
let throttleAjax = throttle(ajax, 1000);
let inputc = document.getElementById(‘throttle’)
inputc.addEventListener(‘keyup’, function (e) {
throttleAjax(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
- 24
- 25
- 26
- 27
- 28
- 29
- 30
在不断输入时,ajax会按照我们设定的时间,每1s执行一次。
应用场景:
函数防抖(debounce):
- search搜索联想,用户在不断输入值时,用防抖来节约请求资源;
- window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
函数节流(throttle):
- 鼠标不断点击触发,mousedown(单位时间内只触发一次)
- 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断
总结:
- 函数防抖和函数节流都是防止某一时间频繁触发,但原理不一样。
- 函数防抖是某一段时间内只执行一次,而函数节流是间隔时间执行。