js 防抖和节流(阅读这一篇就够了)

防抖(debounce)

所谓防抖,就是指触发事件后,就是把触发非常频繁的事件合并成一次去执行。即在指定时间内只执行一次回调函数,如果在指定的时间内又触发了该事件,则回调函数的执行时间会基于此刻重新开始计算。也就是说,你在一个按钮上连续快速点击1万次用了1小时,也只执行了一次回调

创建utils.js

// -防抖 所谓防抖,就是指触发事件后,就是把触发非常频繁的事件合并成一次去执行。即在指定时间内只执行一次回调函数,
// 如果在指定的时间内又触发了该事件,则回调函数的执行时间会基于此刻重新开始计算。
let timerDebounce = null
export const debounce = (fn, wait = 1000) => {
    
    
    console.log('wait',wait);
	if(timerDebounce) {
    
    
		console.log('防抖状态');
		clearTimeout(timerDebounce)
	}
	let callNow = !timerDebounce
	timerDebounce = setTimeout(() => {
    
    
		timerDebounce = null;
	}, wait)
    if(callNow){
    
    
		console.log('===执行函数===',timerDebounce);
		fn();//执行函数
	}
}

节流(throttle)

所谓节流,是指频繁触发事件时,只会在指定的时间段内执行事件回调,即触发事件间隔大于等于指定的时间才会执行回调函数。也就是说,你在一个按钮上连续快速点击1万次用了1小时,会执行16060*1000/wait 次回调
创建utils.js

let timerThrottle = null
// -节流 所谓节流,是指频繁触发事件时,只会在指定的时间段内执行事件回调,即触发事件间隔大于等于指定的时间才会执行回调函数。
export const throttle = (fn, wait = 1000) => {
    
    
	console.log('throttle',timerThrottle);
	console.log('wait',wait);
	if(timerThrottle != null){
    
    
		console.log('节流状态');
		return;
	}else{
    
    
		console.log('===执行函数===',timerThrottle);
		fn();//执行函数
	}
    timerThrottle = setTimeout(() => {
    
    
        console.log('节流结束',timerThrottle);
		timerThrottle = null;
    }, wait)
}

在页面中使用

<template>
	<view>
		<view style="margin-top:80rpx;">
			<view style="width:200rpx;">
				<button 
				type="default" 
				@tap="buttonTap">防抖</button>
			</view>
		</view>
	</view>
</template>
<script>
import {
    
    debounce} from '@/common/js/utils.js'
export default {
    
    
	data() {
    
    
		return {
    
    
		}
	},
	methods:{
    
    
		buttonTap(){
    
    
			debounce(()=>{
    
    
				console.log('debounce,这里可执行你想要的接口请求等动作');
			},3000)
		}
	}
}
</script>
<template>
	<view>
		<view style="margin-top:80rpx;">
			<view style="height:2000px; width:750rpx; background-color: #006065;">
				滚动页面试试节流~~
			</view>
		</view>
	</view>
</template>
<script>
import {
    
    throttle} from '@/common/js/utils.js'
export default {
    
    
	data() {
    
    
		return {
    
    
			// 延时器对象
			scrollTimer : null
		}
	},
	methods:{
    
    },
	onPageScroll:function(e){
    
    
		throttle(()=>{
    
    
			console.log('throttle,这里可执行你想要的接口请求等动作');
		},3000)
	}
}
</script>
<style>
</style>

猜你喜欢

转载自blog.csdn.net/qq_17355709/article/details/126571173