美文网首页
防抖与节流

防抖与节流

作者: RedLee666 | 来源:发表于2019-10-01 07:16 被阅读0次
    <div id="content"
    style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;font-size:80px;">
    </div>
    
    let num = 1;
    let content = document.getElementById('content');
    function count() {
      content.innerHTML = num++;
    };
    content.onmousemove = throttle2(count, 500);
    
    //防抖非立即执行版本:
    function debounce1(fun, wait) {
        let t;
        return function () {
        let context = this, args = arguments;
            t ? clearTimeout(t) : undefined;
            t = setTimeout(() => {
                fun.apply(context, args);
            }, wait);
        }
    }
    //防抖立即执行版本
    function debounce2(fun, wait) {
        let t;
        return function () {
            let context = this, args = arguments;
            t ? clearTimeout(t) : undefined;
            let callNow = !t;
            t = setTimeout(() => {
               t = null;
            }, wait)
            if (callNow) fun.apply(context, args)
        }
    }
    
    //节流时间戳版本
    function throttle1(fun, wait) {
        let last = 0;
        return function () {
            let context = this, args = arguments;
            et now = Date.now();
            if (now - last > wait) {
                fun.apply(context, args);
                last = now;
            }
        }
    }
    
    //节流定时器版本
    function throttle2(fun, wait) {
       let t;
        return function () {
            let context = this, args = arguments;
             if (!t) {
                 t = setTimeout(() => {
                     t = null;
                     fun.apply(context, args);
                 }, wait)
             }
        }
    }
    

    相关文章

      网友评论

          本文标题:防抖与节流

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