zoukankan      html  css  js  c++  java
  • 防抖和节流

    什么情况下需要防抖和节流:理论上高频触发就需要防抖和节流,例如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))
  • 相关阅读:
    SVN 图标消失
    svn 图标不显示
    wamp 局域网访问
    php程序 注册机制
    ThinkphpCMF笔记
    thinkphp缓存
    wampserver与 thinkphp 安装
    js function集合
    php function集合
    php sleep
  • 原文地址:https://www.cnblogs.com/wchjdnh/p/10944734.html
Copyright © 2011-2022 走看看