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

节流和防抖 #11

Open
Pieces312 opened this issue Sep 21, 2020 · 0 comments
Open

节流和防抖 #11

Pieces312 opened this issue Sep 21, 2020 · 0 comments

Comments

@Pieces312
Copy link
Owner

节流(throttle):当用户在反复触发一些事件(鼠标滚动事件等)时,需要指定一个“巡视”的时间间隔,在这个时间间隔内,无论触发多少次都不会执行,只有在时间间隔上触发才会执行回调函数。

function throttle(fn, threshold = 200) {
  let timer = null
  let start = new Date().getTime()

  return function () {
    let current = new Date().getTime() - 0
    timer && clearTimeout(timer)
    
    if (current - start >= threshold) {
      fn.call(this)
      start = current
    } else {
      timer = setTimeout(fn.call(this), threshold)
    }
  }
}

const handleMouse = throttle(function (e) {
  console.log(e.pageX, e.pageY)
})

document.body.addEventListener('mousemove', handleMouse)

防抖(debouce):给定一个固定时间,如果开始触发动作并在这个时间内没有再次触发该动作,就执行一次。否则将重新计算时间。

function debouce(fu, delay = 200) {
  let timeout = null

  return function () {
    timeout && clearTimeout(timeout)
    timeout = setTimeout(fn.call(this), delay)
  }
}

const handleChange = debouce(function() {
  console.log('开始触发了!')
})

document.getElementByID('root').addEventListener('input', handleChange)

文章链接:https://juejin.im/post/6844904136064925704

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