uniapp:函数节流和防抖的使用

Posted 久天.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了uniapp:函数节流和防抖的使用相关的知识,希望对你有一定的参考价值。

防抖:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。

debounce: function(fun, delay) {
	return function(args) {
		let that = this;
		let _args = args;
		clearTimeout(fun.id);
		fun.id = setTimeout(() => {
			fun.call(that, _args)
		}, delay)
	}
}

节流:规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。

throttle: function(fn, delay) {
	let timer = true;
	return function(args) {
		let that = this;
		let _args = arguments;
		if(!timer){
		   return false;
		}
		timer = false;
		setTimeout(() => {
			fn.apply(that, _args)
			timer = true;
		}, delay)
	}
}

使用

click: debounce(function() {
    
    console.log('业务代码')

}, 3000)


click: throttle(function() {
    
    console.log('业务代码')

}, 3000)

 

以上是关于uniapp:函数节流和防抖的使用的主要内容,如果未能解决你的问题,请参考以下文章

节流和防抖的区别,以及如何实现

节流和防抖的实现

19节流和防抖的区别以及应用场景的理解

lodash的防抖和节流方法

JS的防抖和节流

JavaScript节流和防抖