Extremely simple throttling and anti-shake, easy to understand

Throttling means that the function is executed only once in a certain period of time.

The implementation logic of this function:

1. No matter how many times the button is clicked within two seconds, the function is only executed once, so a judgment is required to judge whether 2 seconds have passed.

2. It is only executed once in two seconds, which involves time, so a timer setTimeout() is also needed

Ok, after the analysis, you can start writing code

<template>
	<view>
		<button @click="HandelJieliu">{
   
   {number}}</button>
		<button @click="fangdou">{
   
   {age}}</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				number:20,
				age:100,
				jieliu:null,
				fangdou:null
				
			}
		},
		methods: {
            //节流函数
			HandelJieliu(){
				if(this.jieliu){ //判断setTimeout()定时器在两秒内存在否,存在就返回什么都不做
					return 
				}else{//如果定时器不存在,就创建一个定时器
					this.number +=1
					this.jieliu = setTimeout(()=>{
						this.jieliu = null //两秒后清除定时器,等待下一次的点击
					},2000)
				}
			},
            //防抖函数
			HandleFangdou(){
				clearTimeout(this.fangdou)
				this.fangdou = setTimeout(()=>{
					this.age +=1
				},1000)
			}
		}
	}
</script>

<style>

</style>

Anti-shake Just like returning to the city in the glory of the king, as long as you click the returning to the city, the timing will restart. No matter how many times you click the returning to the city button, only the last returning to the city is valid.

Function implementation logic:

1. Each click will re-trigger the event and restart the timing, so a function to clear the timer is needed

clearTimeout()

2. Timing is required, so a timing function is required, setTimeout()

<template>
	<view>
		<button @click="HandelJieliu">{
   
   {number}}</button>
		<button @click="fangdou">{
   
   {age}}</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				number:20,
				age:100,
				jieliu:null,
				fangdou:null
				
			}
		},
		methods: {
			//节流函数
			HandelJieliu(){
				if(this.jieliu){ //判断setTimeout()定时器在两秒内存在否,存在就返回什么都不做
					return 
				}else{//如果定时器不存在,就创建一个定时器
					this.number +=1
					this.jieliu = setTimeout(()=>{
						this.jieliu = null //两秒后清除定时器,等待下一次的点击
					},2000)
				}
			},
			//防抖函数
			HandleFangdou(){
				clearTimeout(this.fangdou) //每次都需要先清空定时器
				this.fangdou = setTimeout(()=>{ //定时器函数,1秒后执行
					this.age +=1
				},1000)
				//整个逻辑就是每一次点击都先清空计时器,让上一次的计时失效,当不在点击时就会执行
				//最后一次定时函数。
			}
		}
	}
</script>

<style>

</style>

Guess you like

Origin blog.csdn.net/weixin_44235659/article/details/128442409