节流函数

56 阅读1分钟

节流函数:当持续触发事件的时候,保证一段时间内,只调用一次事件处理函数,一段时间内 只做一件事。就是说:哪怕你在一秒内点击了一百次,程序也只执行一次 实际应用:表单的提交 典型的案例就是鼠标不断点击触发,规定在n秒内多次点击只有一次生效 实现代码如下:

<script>
	function thro(func,wait){
		let timerOut
		return function(){
                    if(!timerOut){
                        timerOut = setTimeout(function(){
                            func()
                            timerOut = null
                        },wait)
                    }
		}
	}
	function handle(){
		console.log(Math.random());
	}
	document.getElementById('button').onclick = thro(handle,2000)
</script>