javascript的函数防抖

javascript的函数防抖

  1. 就是我们对一件事件,规定在一定的时间内(5000毫秒),重复触发这个事件
  2. 我们就只触发一次,而且是最后一次。这里我是称为频繁操作
  3. 如果上一次操作,和当前的的操作时间相差大于5000毫秒,我就会认为是需要触发两次。

因为我这里模拟的是用定时器来完成的,所以需要写一个函数来管理这个定时器(清除定时器)

function removeTime(time) {
    
    
	clearTimeout(time) // 清除这个定时器
	return null
}

具体的逻辑

  1. 当我们点击发送按钮就执行send函数
  2. 但是我们需要限制频繁操作
<button id="btn">发送</button>
<script>
	let btn = document.getElementById('btn');
	function send() {
      
      
		console.log('发送中...')
	}
	function deal(func, time) {
      
      
		let betweenTime = null
		return function open(...params) {
      
      
			// 每一次点击,我们都会把当前的定时器清除.
			betweenTime = removeTime(betweenTime) // 清除定时器
			betweenTime = setTimeout(() => {
      
      
				func.call(this, ...params)
				// 当当前的定时器执行完了,也是需要清除这个定时器的
				betweenTime = removeTime(betweenTime)
			}, time) // 然后再定义一个定时器
		}
	}
	btn.onclick = deal(send, 5000)
</script>

猜你喜欢

转载自blog.csdn.net/webMinStudent/article/details/121065596