應(yīng)用場景:
防抖:
1.search搜索聯(lián)想拜鹤,用戶在不斷輸入值時徽千,用防抖來節(jié)約ajax請求忠藤。
2.滾動條滾動的時候觸發(fā)事件
//防抖實例
//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)
}
節(jié)流:
1.鼠標(biāo)不斷點擊觸發(fā)被环,mousedown(單位時間內(nèi)只觸發(fā)一次)
2.上拉觸底加載更多
//節(jié)流實例
//ajax請求
function click(content) {
console.log('點擊了參數(shù)是:' + 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)
//鼠標(biāo)點擊事件
function onClick(e) {
debounceAjax(e.target.value)
}