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

去抖 | 节流 #85

Open
yongheng2016 opened this issue Feb 28, 2018 · 0 comments
Open

去抖 | 节流 #85

yongheng2016 opened this issue Feb 28, 2018 · 0 comments

Comments

@yongheng2016
Copy link
Owner

yongheng2016 commented Feb 28, 2018

节流

函数节流能使得连续的函数执行,变为 固定时间段 间断地执行。
(通常情况下此函数为 DOM 事件的回调函数)

function throttle(method, time, context) {
  if (method.tId){return}
  method.call(context)
  method.tId = true
  setTimeout(function() {
    method.tId = false
  }, time);
}
xxx
throttle = function (fn, time){
  let cd = false
  return function (){
    if (cd){return}
    fn.call()
    cd = true
    setTimeout(() => {cd = false},time)
  }
}
fn = function (){
  console.log('a')
}
for (var i=0; i<100; i++){
  throttle(fn, 10000)()
}

去抖

函数去抖就是对于一定时间段的连续的函数调用,只让其执行一次。
用户输入搜索、滚动加载

function debounce(method, time, context) {
  clearTimeout(method.tId);
  method.tId = setTimeout(function() {
    method.call(context);
  }, time);
}
xxx
function debounce(fn, time, context) {
  let timer = undefined
  return function (){
     if (timer !== undefined){
        window.clearTimeout(timer)
     }
     timer = setTimeout( () => {
     fn.call()
     }, time)
  }
}

function print() {
  console.log('hello world',);
}

window.onscroll = function() {
  debounce(print, 1000);
};

@yongheng2016 yongheng2016 changed the title 防抖 | 节流 去抖 | 节流 Mar 19, 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