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

实现一个防抖函数 #336

Open
Sogrey opened this issue Dec 13, 2020 · 0 comments
Open

实现一个防抖函数 #336

Sogrey opened this issue Dec 13, 2020 · 0 comments

Comments

@Sogrey
Copy link
Owner

Sogrey commented Dec 13, 2020

// 思路:在规定时间内未触发第二次,则执行
function debounce (fn, delay) {
  // 利用闭包保存定时器
  let timer = null
  return function () {
    let context = this
    let arg = arguments
    // 在规定时间内再次触发会先清除定时器后再重设定时器
    clearTimeout(timer)
    timer = setTimeout(function () {
      fn.apply(context, arg)
    }, delay)
  }
}

function fn () {
  console.log('防抖')
}
addEventListener('scroll', debounce(fn, 1000)) 

什么是防抖和节流?有什么区别?如何实现? #110

@Sogrey Sogrey added this to javascript in Web面经题 Dec 13, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Web面经题
javascript
Development

No branches or pull requests

1 participant