当前位置:网站首页>Implement the throttling de dithering function

Implement the throttling de dithering function

2022-06-24 03:29:00 HZFEStudio

Complete high frequency question bank warehouse address :https://github.com/hzfe/awesome-interview

Complete high frequency question bank reading address :https://febook.hzfe.org/

throttle

1. Basic concepts

throttle(func, wait)

Every time wait At most once in milliseconds func.

2. Application scenarios

  • Real time association when entering the search box .
  • monitor scroll Event calculation location information .

3. flow chart

4. Write code

function throttle(func, wait) {
  let lastTime = 0;
  let timer = null;

  return function () {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    let self = this;
    let args = arguments;
    let nowTime = +new Date();

    const remainWaitTime = wait - (nowTime - lastTime);

    if (remainWaitTime <= 0) {
      lastTime = nowTime;
      func.apply(self, args);
    } else {
      timer = setTimeout(function () {
        lastTime = +new Date();
        func.apply(self, args);
        timer = null;
      }, remainWaitTime);
    }
  };
}

To shake

1. Basic concepts

debounce(func, wait)

Delay since last trigger wait Millisecond call func.

2. Application scenarios

  • When registering, check whether the user name is occupied after entering it .
  • monitor resize Event calculation size information .

3. flow chart

4. Write code

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

  return function () {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    let self = this;
    let args = arguments;

    timer = setTimeout(function () {
      func.apply(self, args);
      timer = null;
    }, wait);
  };
}
原网站

版权声明
本文为[HZFEStudio]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/10/20211003163811133l.html