js アンチシェイクとスロットル (この記事を読んでください)

手ぶれ補正(デバウンス)

いわゆるアンチシェイクとは、イベントをトリガーした後、非常に頻繁にトリガーされるイベントが 1 つの実行にマージされて実行されることを意味します。つまり、コールバック関数は指定された時間内に 1 回だけ実行され、指定された時間内に再度イベントがトリガーされた場合は、その時点に基づいてコールバック関数の実行時間が再計算されます。つまり、ボタンを 10,000 回素早く連続してクリックし、それに 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();//执行函数
	}
}

スロットル

いわゆるスロットリングとは、イベントが頻繁にトリガーされる場合、イベント コールバックは指定された期間内のみ実行されることを意味します。つまり、イベントをトリガーする間隔が指定された時間以上になるまで、コールバック関数は実行されません。 。つまり、ボタンを 10,000 回続けてクリックして 1 時間かかる場合、1 60 60*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