Commonly used anti-shake functions and calls of uniapp WeChat applets

Look at the code first, just copy and use it. (Anti-shake is generally used for buttons to avoid multiple calls such as login, purchase, etc., such as clicking the purchase button multiple times may generate multiple order information under slower Internet speeds, etc.)

Here is just a simple process of encapsulation call, if you use our official product uview, anti-shake reference: throttle & debounce throttle anti-shake .

You need to define a js file first copy the following code

//防抖原理:一定时间内,只有最后一次操作,再过times毫秒后才执行函数
let timeout = null;
				// 执行函数  时间      是否立即执行
function debounce(func, times = 500, immediate = false) {
    
    
	// 清除定时器
	if (timeout !== null) clearTimeout(timeout);
	// 立即执行,传true 则不进行防抖 一般不传递第三个参数
	if (immediate) {
    
    
		var callNow = !timeout;
		timeout = setTimeout(function() {
    
    
			timeout = null;
		}, times);
		if (callNow) typeof func === 'function' && func();
	} else {
    
    
		// 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时times毫秒后执行func回调方法
		timeout = setTimeout(function() {
    
    
			typeof func === 'function' && func();
		}, times);
	}
}

export default debounce

The calling method is as follows

import debounce from '配置路径'
methods:{
    
    
	//不需要自定义 时间和立即执行时
	getCode:debounce(function(){
    
    
		//您的逻辑操作
	})
	//需要自定义 时间和立即执行时
	getCode:debounce(function(){
    
    
		//您的逻辑操作
	},1000,true)
}

If you have any questions about uniapp or you don’t understand this method, you can leave a message, I will reply as soon as possible and help you solve it.

Guess you like

Origin blog.csdn.net/weixin_47821281/article/details/113931696