应用场景:
防抖:
1.search搜索联想,用户在不断输入值时,用防抖来节约ajax请求。
2.滚动条滚动的时候触发事件
//防抖实例
//ajax请求
function ajax(content) {
console.log(content)
console.log('ajax request ' + content)
}
//利用闭包将timer存在自己得作用域
function debounce(fun, delay) {
let timer = null;
return function (args) {
let that = this
let _args = args
clearTimeout(timer)
timer = setTimeout(function () {
fun.call(that, _args)
}, delay)
}
}
//生成闭包
let debounceAjax = debounce(ajax, 3000)
//输入框change事件
function inputChange(e) {
debounceAjax(e.target.value)
}
节流:
1.鼠标不断点击触发,mousedown(单位时间内只触发一次)
2.上拉触底加载更多
//节流实例
//ajax请求
function click(content) {
console.log('点击了参数是:' + content)
}
//利用闭包将timer存在自己得作用域
function debounce(fun, delay) {
let can = false;
return function (args) {
let that = this
let _args = args
if(can) return
can = true
timer = setTimeout(function () {
fun.call(that, _args)
can = false
}, delay)
}
}
//生成闭包
let debounceAjax = debounce(ajax, 3000)
//鼠标点击事件
function onClick(e) {
debounceAjax(e.target.value)
}
网友评论