手写防抖和节流

    const box=document.querySelector('#box')
            let i=1
            function move(){
                
                box.innerHTML=i++
            }
            // 手写防抖函数,debounce(调用的函数,等待时间)
            function debounce(fun,t){
                let timer
                return function(){
                    if(timer) clearTimeout(timer)
                    timer=setTimeout(function(){
                        fun()
                    },t)
                }
            }
            // box.addEventListener('mousemove',debounce(move,500))
            // 手写节流函数,thorttle(调用的函数,等待时间)
            function thorttle(fn,t){
                let timer=null
                return function(){
                    if(!timer){
                        timer=setTimeout(function(){
                            fn()
                            timer=null
                        },t)
                    }
                }
            }
            box.addEventListener('mousemove',thorttle(move,500))

 

fd() {
			let that = this
			clearTimeout(this.fdFlag)
			this.fdFlag = setTimeout(() => {
				that.payAct()
				that.fdFlag = null
			}, 500)
			// 在此时间段触发几次事件,就延迟触发几次,并只触发最后一次事件。
		},

  

posted @ 2023-03-23 16:54  小闫的姑娘  阅读(13)  评论(0编辑  收藏  举报