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

防抖&节流 #19

Open
K-Kevin opened this issue Apr 26, 2020 · 0 comments
Open

防抖&节流 #19

K-Kevin opened this issue Apr 26, 2020 · 0 comments

Comments

@K-Kevin
Copy link
Owner

K-Kevin commented Apr 26, 2020

防抖函数

防抖,即在事件触发了 wait 的延时后才执行,但如果在 wait 期间再次执行,那么会被重置,重新开始,等于说如果我把 wait 设置为 3秒,如果3秒内我不停的触发事件,那么事件就不会被触发
function debounce(func, wait = 300) {
    let timeout = null;
    return function () {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            func.apply(this, arguments);
        }, wait);
    };
}

节流

防抖是延迟执行,而节流是间隔执行,函数节流即每隔一段时间就执行一次,实现原理为设置一个定时器,约定xx毫秒后执行事件,如果时间到了,那么执行函数并重置定时器,和防抖的区别在于,防抖每次触发事件都重置定时器,而节流在定时器到时间后再清空定时器

定时器实现:等待特定时间后执行,停止后,如果还在 wait 中,则还会执行最后一次

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

时间戳实现:先执行事件,再等待特定时间后执行

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

时间戳结合定时器:首次执行,并且最后一次也会执行

// 节流 
function throttle(func, wait=500) {
    let previous = 0;
    let context, args, time, remaining;    
    return function() {
      let now = +new Date();
      context = this;
      args = arguments;
      remaining = wait - (now - previous)// 剩余的还需要等待的时间
      if (remaining <= 0) {
        func.apply(context, args);
        previous = now // 重置“上一次执行”的时间
      } else {
        if (time) {
          clearTimeout(time);
        }
        time = setTimeout(() => {
          func.apply(context, args);
          time = null;
          previous = +new Date() // 重置“上一次执行”的时间
        }, remaining) //等待还需等待的时间
      }
  }
}
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