Handwriting anti-shake, throttling :
-
Anti-shake: Execute the callback after n seconds after the event is triggered. If the event is triggered again within n seconds, the timing will be restarted
-
Throttling: Within the specified time, there can only be one callback that triggers the event, and it will not take effect if it is triggered repeatedly within the unit time
Application scenario:
-
Anti-shake: input box input (input)...
-
Throttle: browser window changes (resize), page scrolling (scroll), dragging (drag)...
anti-shake
function debounce(fn, delay) {
let timer = null;
return function () {
if(timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay)
}
}
Throttling:
function throttle(fn, delay) {
let timer = null;
return function () {
if(timer) return;
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay)
}
}
Call method:
const btn = document.querySelector('button')
btn.addEventListener('click', debounce(function () {
console.log('发财小手点个关注')
}, 1000, true))
vue version
<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>