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

函数节流和防抖的概念以及常见的使用场景 #9

Open
lxinr opened this issue Apr 22, 2019 · 1 comment
Open

函数节流和防抖的概念以及常见的使用场景 #9

lxinr opened this issue Apr 22, 2019 · 1 comment

Comments

@lxinr
Copy link
Owner

lxinr commented Apr 22, 2019

节流

在一个单位时间内,无论触发多少次方法,最多只有一次生效

实现

function throttle(fn, interval = 1000) {
  let timer = 0,
    start = +new Date()
  return (...args) => {
    const cur = +new Date()

    clearTimeout(timer)
    console.log('time---', cur - start)
    // 间隔时长大于interval
    if(cur - start >= interval) {
      fn.apply(this, args)
      start = cur
    } else {
      timer = setTimeout(() => {
        // 让方法在事件已经脱离以后再执行一次
        fn.apply(this, args)
      }, interval)
    }
  }
}

常见使用场景

1、输入框输入值,防止频繁触发事件

2、window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次

防抖

在事件被触发一定时间后再执行回调,如果在这一定时间内又被触发,则重新计时

实现

function debounce(fn, wait = 200) {
  let timer = 0
  return (...args) => {
    if(timer) clearTimeout(timer)
    timer = setTimeout(() => fn.apply(this, args), wait)
  }
}

常见使用场景

1、鼠标移动时,间隔一定时间段返回坐标信息

2、滚动事件、滑动事件,获取滚动或滑动距离

@lxinr
Copy link
Owner Author

lxinr commented Feb 2, 2021

防抖函数优化版本

/**
 * 函数防抖
 *
 * @author liux
 * @date 2021-02-02
 * @param {function} fn
 * @param {number} [wait=300]
 * @param {boolean} [immediate=false]
 * @returns {function}
 */
function debounce (fn, wait = 300, immediate = false) {
  let timer
  return function (...args) {
    if (timer) clearTimeout(timer)

    if (immediate) {
      const imTimer = !timer
      timer = setTimeout(() => {
        timer = null
      }, wait)
      if (imTimer) fn.apply(this, args)
    } else {
      timer = setTimeout(() => {
        fn.apply(this, args)
      }, wait)
    }
  }
}

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