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

83.源码实现系列-写防抖节流 #83

Open
webVueBlog opened this issue Feb 7, 2023 · 0 comments
Open

83.源码实现系列-写防抖节流 #83

webVueBlog opened this issue Feb 7, 2023 · 0 comments

Comments

@webVueBlog
Copy link
Member

1.防抖和节流区别=>

防抖是 N 秒内函数只会被执行一次,如果 N 秒内再次被触发,则重新计算延迟时间(举个极端的例子 如果 window 滚动事件添加了防抖 2s 执行一次 如果你不停地滚动 永远不停下 那这个回调函数就永远无法执行)
节流是规定一个单位时间,在这个单位时间内最多只能触发一次函数执行(还是滚动事件 如果你一直不停地滚动 那么 2 秒就会执行一次回调)

2.防抖怎么保证 事件延迟执行 并且在规定时间内再次触发需要清除 这个很容易就想到了 setTimeout

3.节流怎么保证 在单位时间内触发了一次就不再生效了 可以用一个 flag 标志来控制

// 防抖
function debounce(fn, delay) {
 let timer;
 return function() {
  var args = arguments;
  if (timer) {
   clearTimeout(timer);
  }
  timer = setTImeout(() => {
    fn.apply(this, args);
  }, delay);
 }
}

window.addEventListener(
 "scroll",
 debounce(() => {
   console.log(111);
 }, 1000)
);

// 节流
// 1. 设置一个标志

function throttle(fn, delay) {
 let timer;
 let flag = true;
 return () => {
  if (!flag) return;
  flag = false;
  timer = setTimeout(() => {
   fn();
   flag = true;
  }, delay);
 };
}

// 2. 使用时间戳
function throttle(fn, delay) {
 let startTime = new Date();
 return () => {
  let endTime = new Date();
  if (endTime - startTime >= delay) {
    fn();
    startTime = endTime;
  } else {
    return;
  }
 };
}

window.addEventListener(
  "scroll",
  throttle(() => {
    console.log(111);
  }, 1000)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant