防抖节流函数封装

1,966 阅读2分钟

emmm 老生常谈的两个实用型函数 不用多做说明了 自己写了一遍 注释很详细了

// 节流 使一个函数在一定的时间内只会触发一次
// 可以用在上拉加载更多 触底触发函数中  减少函数触发频率
export function throttle(fn,delay){
	//传入两个参数 
	//fn 这个是触发函数之后你要执行的函数
	//delay  这个是延时的时间
	let timer = null

	//返回一个函数出去  这个函数可以接收参数来执行你的下一步操作
	return function(){

		//保存this对象
		let _this = this
		//传入的参数
		let arg = arguments

		if(timer){
			return
		}else{
			//触发节流函数
			timer = setTimeout(()=>{
				//延迟结束 重置timer 清除延时器
				timer = null
				//执行你想要的操作
				fn.apply(_this,arg)
			},delay)
		}
	}
}
//节流 时间戳形式
export function throttle_timestamp(fn,delay){
	//初始时间点
	let prev = 0

	//返回一个函数出去  这个函数可以接收参数来执行你的下一步操作
	return function(){

		//保存this对象
		let _this = this
		//传入的参数
		let arg = arguments
		//当前时间戳
		let now = new Date().getTime()

		if(now - prev > delay){
			//改变初试时间
			prev = now
			//执行你想要的操作
			fn.apply(_this,arg)
		}else{
			return
		}
	}
}
//防抖 
//主要是在事件频繁触发的地方使用 比如搜索框 可以节省请求资源
export function debounce(fn,delay){
	//传入两个参数
	//fn 这个是触发函数之后你要执行的函数
	//delay  这个是延时的时间
	let timer = null

	//返回一个函数出去  这个函数可以接收参数来执行你的下一步操作
	return function(){

		//保存this对象
		let _this = this
		//传入的参数
		let arg = arguments

		//清除延时器
		clearTimeout(timer);
		//设置一个延时器 延时结束进行操作
		timer = setTimeout(()=>{
			//执行你想要的操作
			fn.apply(_this,arg)
		},delay)

	}
}

使用

import {throttle,debounce} from '@/common/throttle.js'

export default {
		data() {
			return {
				num:0,
				name:'',
				fnn:'',
				fnn2:''
			};
		},
		methods:{
			fn(){
				// console.log(e)
				console.log(11111111111)
				this.num += 1
			}
		},
		onLoad(){
			let t = new Date().getTime()
			console.log(date.time('w',t))
			this.fnn = throttle(this.fn,2000)
			this.fnn2 = debounce(this.fn,2000)
		}
	}

把引入的防抖节流函数保存到变量里那么在html里面的事件里直接用这个变量就好了

<view class="content">
		<button @click="fnn">测试{{num}}</button>
		<button @click="fnn2">测试{{num}}</button>
	</view>

快快乐乐又摸了一天鱼。。。