手写防抖、节流:
-
防抖:事件触发n秒后再执行回调,若在n秒内事件又被触发,则重新计时
-
节流:在指定时间内,只能有一次触发事件的回调执行,若在单位时间内重复触发则不生效
应用场景:
-
防抖:输入框输入(input)...
-
节流:浏览器窗口变化(resize)、页面滚动(scroll)、拖拽(drag)...
防抖
function debounce(fn, delay) {
let timer = null;
return function () {
if(timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay)
}
}
节流:
function throttle(fn, delay) {
let timer = null;
return function () {
if(timer) return;
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay)
}
}
调用方法:
const btn = document.querySelector('button')
btn.addEventListener('click', debounce(function () {
console.log('发财小手点个关注')
}, 1000, true))
vue版本
<template>
<view class=”fanjun-jsSkill”>
<view class=”oneSkill”>
<view class="fdButton btn" @click="fd">
防抖按钮
</view>
<view class="jlButton btn" @click="jl">
节流按钮
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
fdFlag: null,
jlFlag: true
}
},
methods: {
fd() {
let that = this
clearTimeout(this.fdFlag)
this.fdFlag = setTimeout(() => {
that.fdDoing()
that.fdFlag = null
}, 800)
// 在此时间段触发几次事件,就延迟触发几次,并只触发最后一次事件。
},
fdDoing() {
console.log(‘防抖事件触发’)
},
jl() {
let that = this
if(!this.jlFlag) {
return
}
this.jlFlag = false
setTimeout(() => {
that.jlDoing()
that.jlFlag = true
},1200)
// 一定时间内,只执行一次有效事件
},
jlDoing() {
console.log(‘节流事件触发’)
}
}
}
</script>
<style>
.oneSkill {
display: flex;
flex-direction: row;
justify-content: space-around;
}
.btn {
width: 160rpx;
height: 46rpx;
background-color: #007AFF;
color: #FFFFFF;
border-radius: 20rpx;
text-align: center;
line-height: 46rpx;
vertical-align: middle;
}
</style>