今天研究了一下scroll 的节流 和 防抖,写了一个demo,最后发现被触发的顺序改变了,但是被触犯的次数都是69,既然被触发的次数都相同请问节流和防抖到底有什么意义呢?代码如下
<template>
<div class="container" style="height: 667px;">
<div class="content" style="height: 3000px"></div>
<a href="javascript: void(0)"
@click="_getNum"
style="color: blue; font-size: 20px;"
>点击</a>
</div>
</template>
export default {
data(){
return {
a: 0,
b: 0,
c: 0
}
},
mounted(){
var container = document.getElementsByClassName('container')[0]
container.addEventListener('scroll', () => {
this.a++
this.debounce(() => {
this.b++
}, 250)
this.throttling(() => {
this.c++
}, 500, 1000)
})
},
methods: {
_getNum(){
console.log(this.a, this.b, this.c)
},
// 防抖
debounce(func, wait, immediate) {
var timeout
return function(){
var context = this,
args = arguments
var later = function(){
timeout = null
if(!immediate){
func.apply(context, args)
}
}
var callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if(callNow){
func.apply(context, args)
}
}()
},
// 节流
throttling(fn, wait, maxTimelong) {
var timeout = null,
startTime = Date.parse(new Date);
return function() {
if(timeout !== null) clearTimeout(timeout);
var curTime = Date.parse(new Date);
if(curTime-startTime>=maxTimelong) {
fn() && (startTime = curTime)
} else {
timeout = setTimeout(fn, wait);
}
}()
}
}
}
然后滚动浏览器,结果如下
用法不对,代码也不对
你返回的是undefined,调用时每次
fn()
都从新生成一个timer
你的节流跟防抖跟普通函数没有区别