防抖和节流

什么情况下需要防抖和节流:理论上高频触发就需要防抖和节流,例如onresize,onscroll事件。防抖和节流是两种解决高频触发影响用户体验的解决两种方案

用两幅图和几句简单的话以及简单的代码实现:

防抖:一句话就是"不要干扰我"。这就跟强迫症很像,一受到不和谐的干扰就重新来过  (触发事件后,处理函数过段事件触发【setTimeout】,但是如果在这段时间中又触发事件,这段时间就会重新来过)

function debounce(fn,delay){
            var timeId = null;
            return function(){
                if(timeId){
                    clearTimeout(timeId)
                }
                    timeId = setTimeout(fn,delay)
            }
        }

        function handle(){
            console.log('我是处理函数')
        }
window.addEventListener('resize',debounce(handle,1000))

节流:我行我素型,他强任他强,我有自己的步伐 (不管你触发几次,我就每隔一段时间执行一次)

function throttle(fn,delay){
            var timeId = null
            return function(){
                if(!timeId){
                    timeId = setTimeout(function(){
                        handle(fn)
                        timeId = null
                    },delay)
                }
            }
        }
        function handle(){
            console.log('我是处理函数')
        }
        window.addEventListener('resize',throttle(handle,1000))
原文地址:https://www.cnblogs.com/wchjdnh/p/10944734.html