dashengzi66 / note

学习笔记
0 stars 0 forks source link

防抖&节流 #5

Open dashengzi66 opened 3 years ago

dashengzi66 commented 3 years ago

防抖

定义: 是指触发事件后在n秒内函数只能执行1次, 如果在n秒内又触发了事件, 则会重新计算函数执行时间

<div id="content" style="height:150px;line-height:150px;text-align:center; color: #fff;
background-color:#ccc;font-size:80px;"></div>

方案1--包含立即执行

   let num = 1;
    let content = document.getElementById('content');

    function count() {
      content.innerHTML = num++;
    }
    content.onmousemove =debounce(count,300,false);

    function debounce(func, wait = 300, immediate = false) {
      let timer = null;

      return function anonymous(...params) {
        let now = immediate && !timer;
        //每次点击都把之前设置的定时器清除掉
        clearInterval(timer)
        //重新设置一个新的定时器监听wait事件内是否触发第二次
        timer = setTimeout(() => {
          timer = null; //垃圾回收机制
          //wait这么久的等待中,没有触发第二次
          !immediate ? func.call(this, ...params) : null;
        }, wait);

        //如果是立即执行
        now ? func.call(this, ...params) : null;
      }
    }
dashengzi66 commented 3 years ago

节流

定义: 指连续触发事件但是在 n 秒中只执行一次函数

<div id="content" style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;
font-size:80px;"></div>

方案1--时间戳

function throttle(func, wait) {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}
content.onmousemove = throttle(count,1000);

方案2--定时器

function throttle(func, wait) {
    let timeout;
    return function() {
        let context = this;
        let args = arguments;
        if (!timeout) {
            timeout = setTimeout(() => {
                timeout = null;
                func.apply(context, args)
            }, wait)
        }

    }
}
content.onmousemove = throttle(count,1000);