首页前端工具函数Throttle节流与Debounce防抖

Throttle节流与Debounce防抖

分类前端工具函数时间2022-03-15 11:46:55发布RustStream浏览124
摘要:// 防抖 function debounce(fn, wait { let timer = null; return function( { clearTimeout(timer ; timer = setTimeout(( => { fn.apply(this, arguments }, wait } } // 节流 function throttle(fn, wait { let time = 0; return function( { let now = Date.now( ; let arg = arguments; if(now - time <!--autointro-->...
    // 防抖
    function debounce(fn, wait){
      let timer = null;
      return function(){
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, arguments)
        }, wait)
      }
    }

    // 节流
    function throttle(fn, wait){
      let time = 0;
      return function(){
        let now = Date.now();
        let arg = arguments;
        if(now - time >= wait){
          fn.apply(this, arg)
          time = now
        }
      }
    }

    function sayHeelo(){
      console.log('Hello,world!')
    }


    document.addEventListener('mousemove', throttle(sayHeelo, 2000))


    const btn = document.getElementsByClassName('btn')[0];
    btn.addEventListener('click', dbounce(sayHeelo, 1000))

本文链接:https://blog.smallhao.fun/?id=22 转载需授权!

分享到:

Chen’Blog版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

JavaScript
验证平台 封装图片懒加载处理函数

游客 回复需填写必要信息
召唤伊斯特瓦尔