美文网首页
节流和防抖

节流和防抖

作者: 小漠穷秋 | 来源:发表于2017-11-15 20:34 被阅读0次

    核心概念:
    1.节流——强制按照需求的间隔去多次执行。
    2.防抖——等待稳定后执行一次。

    这里我们用resize事件的监控来模拟节流和防抖的实现。使用闭包来保留变量。

    案例:
    1.节流函数:
    /*原函数
    window.addEventListener('resize',fn);
    function fn() {
    console.log(Math.random());
    }
    */
    window.addEventListener('resize',throttling(500,3000,fn));//等待稳定时间 强制执行时间
    function fn() {
    console.log(Math.random());
    }
    function throttling(timer,wait,fn) { //一个闭包
    var timeout = null;
    var startTime = Date.parse(new Date);
    return function() {
    if (timeout!=null) clearTimeout(timeout);
    var curTime = Date.parse(new Date);
    if ((curTime - startTime) >= wait) {
    fn();
    startTime = curTime;
    }
    else {
    timeout = setTimeout(fn,timer);
    }
    }
    }

    2.防抖函数:
    /*原函数
    window.addEventListener('resize',fn);
    function fn() {
    console.log(Math.random());
    }
    */

    //防抖改造
    function fn() {
    console.log(Math.random());
    }
    function debounce(fn,timer) { //防抖函数
    console.log(timeout);
    var timeout = null;
    return function() { //使用闭包 一个闭包
    if (timeout != null) {
    console.log(timeout);
    clearTimeout(timeout);
    }
    timeout = setTimeout(fn,timer);
    }
    }
    window.addEventListener('resize',debounce(fn,500));

    应用场景:
    1.节流思想:反复点击,只执行第一次。
    2.防抖思想:反复点击,一次也不执行。稳定后执行一次。

    相关文章

      网友评论

          本文标题:节流和防抖

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