美文网首页
js 防抖动

js 防抖动

作者: 日不落000 | 来源:发表于2019-11-21 16:49 被阅读0次

    问题:针对频繁触发scoll resize绑定的事件函数,有可能短时间多次触发时事件,影响性能。
    思路:多个函数调用合成一次,给定时间后仅调用最后一次

      
      // 包装事件的debounce函数
      debounce = (func, delay)=>{
        let timer = null;    
        console.log('this,',this);
    
        const _that = this;
        return function(){
          console.log('this,',this);
          console.log('_that,',_that);
          let context = _that; // 通过 ‘this’ 和 ‘arguments’ 获取函数的作用域和变量
          let args = arguments; 
          clearTimeout(timer);
          timer = setTimeout(()=>{
            func.apply(context, args);
          }, delay)
        }();
      }
    
      // 当用户滚动时被调用的函数
      foo = ()=>{
        console.log("todo somethind");
        console.log('this,',this);
      }
      
      handleScroll = () => {
          // 元素绑定scoll事件,触发包装函数debounce
        this.debounce(this.foo, 100);
    
      }
      
      componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll);
      }
    
      componentDidMount = async () => {
    
        window.addEventListener('scroll', this.handleScroll);
      }
      
    
    

    参考:
    https://codepen.io/ribuluo000/pen/MWgqpZV

    相关文章

      网友评论

          本文标题:js 防抖动

          本文链接:https://www.haomeiwen.com/subject/ypffuctx.html