Simple anti-shake, throttling to prevent repeated clicks
Anti-shake and throttling are common ways we optimize performance in the development process
<div id="fangdou" style="margin:50px;">
<input style="border:1px solid #38f;padding:10px;" type="button" @click="debounce()" value="防抖按钮">
<input style="border:1px solid #38f;padding:10px;" type="button" @click="throttle" value="节流按钮">
</div>
<script>
export default{
name:"fangdou",
data(){
return{
timeout: false,
lastTime: 0,
now: Number.MAX_VALUE
}
},
methods: {
debounce() {
if (this.timeout) {
clearTimeout(this.timeout)
}
this.timeout = setTimeout(() => {
console.log('发送网络请求防抖');
this.timeout = false
}, 500)
},
throttle() {
if (this.now - this.lastTime >= 1000) {
this.lastTime = +new Date()
this.now = +new Date()
setTimeout(() => {
console.log('发送网络请求节流');
this.now = +new Date()
}, 1000)
}
}
}
}
</script>