Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

防抖和节流 #4

Closed
PolluxLee opened this issue Apr 7, 2018 · 0 comments
Closed

防抖和节流 #4

PolluxLee opened this issue Apr 7, 2018 · 0 comments

Comments

@PolluxLee
Copy link
Owner

PolluxLee commented Apr 7, 2018

防抖(Debounce)

使用场景:对于连续事件响应,只需要执行一次回调

function debounce(func, wait, immediate) {
  var timeId = null;

  return function () {
    
    clearTimeout(timeId);
    // 立即执行
    if (immediate) {
      if (!timeId) func.apply(this, arguments);
      timeId = setTimeout(() => {
        timeId = null;
      }, wait);
    }
    // 停止后执行
    else {
      timeId = setTimeout(() => {
        func.apply(this, arguments);
      }, wait);
    }
  }
}

节流(Throttle)

使用场景:对于连续事件响应,需要间隔一定时间触发回调来控制函数调用频率

function throttle(func, wait) {
  var now, previous = 0;

  return function () {
    now = +new Date();
    if (now - previous > wait) {
      func.apply(this, arguments);
      previous = now;
    }
  }
}

Reference

mqyqingfeng/Blog#22
mqyqingfeng/Blog#26

@PolluxLee PolluxLee changed the title 防抖动(Debouncing)和节流阀(Throttling) 防抖(Debounce)和节流(Throttle) Jun 9, 2018
@PolluxLee PolluxLee changed the title 防抖(Debounce)和节流(Throttle) 防抖和节流 Aug 16, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant