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

防抖与节流 #27

Open
MaMaFish opened this issue Jul 10, 2020 · 0 comments
Open

防抖与节流 #27

MaMaFish opened this issue Jul 10, 2020 · 0 comments

Comments

@MaMaFish
Copy link
Owner

MaMaFish commented Jul 10, 2020

Debounce

function debounce (func, delay) {
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

Throttle

function throttle(fn, interval) {
  let flag = true;
  return funtion(...args) {
    if (!flag) return;
    flag = false;
    setTimeout(() => {
      fn.apply(this, args);
      flag = true;
    }, interval)
  }
}

或者用时间差的方式判断

functionn throttle(fn, interval) {
   let last = null
   return function (...args) {
     let now = Date.now()
     // 还没到时间
     if(now - last < interval) return
     last = now
     fn.apply(this, args)
   }
 }
@MaMaFish MaMaFish changed the title 第27题:防抖与节流 防抖与节流 Dec 10, 2020
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