Javascript防止按钮多次点击的节流函数throttle

问题:

一个按钮点击后执行的异步操作,返回时间不一定,可能会导致多次重复点击。 例:
<!DOCTYPE html>

<html>
<body >  
	<button  onclick="test()" >点击</button>
</body>
<script>
function test(){

	console.log('a click')
	setTimeout( ()=>{
			alert("123")		
		},500)
}
</script>
</html>

多次点击会导致有多个alert

解:

编写一个公共的节流函数,使方法在一段时间内最多调用一次

<!DOCTYPE html>

<html>

<style>
	

</style>

<body >  
	<button  onclick="warp_test()" >点击</button>
</body>

<script>

const throttle = (func,wait) =>{
	let context, args , prevArgs, argsChanged,result;
	let previous = 0
	console.log(123);
	return function (){
		let now,remainning;
		if(wait){
			now = Date.now();
			remaining = wait - (now - previous);
		}
		context = this;
		args = arguments;
		argsChanged = JSON.stringify(args) != JSON.stringify(prevArgs)
		prevArgs = {...args}
		if(argsChanged || wait && (remaining <=0 || remaining > wait)){
			if(wait){
				previous = now ;
			}
			result = func.apply(context,args);
			context = args = null;
		}
		return result
	}

}

function test(){

	console.log('a click')
	setTimeout( ()=>{
			alert("123")		
		},500)
}

const warp_test = throttle(test,500)

</script>

</html>


另:如果严格串行调用可以设置标记位,当异步请求开始时,设置为1(下次的点击不进行请求),结束后设置为0(下次的点击进行请求)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章