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

防抖函数和节流函数 #25

Open
gdutwyg opened this issue Jul 27, 2018 · 0 comments
Open

防抖函数和节流函数 #25

gdutwyg opened this issue Jul 27, 2018 · 0 comments
Labels

Comments

@gdutwyg
Copy link
Owner

gdutwyg commented Jul 27, 2018

防抖

  • 防抖(debounce):设定一个时间间隔,当某个频繁触发的函数执行一次后,在这个时间间隔内不会再次被触发,如果在此期间尝试触发这个函数,则时间间隔会重新开始计算

  • 应用场景:
    1.给按钮加函数防抖防止表单多次提交
    2.文本输入的验证

function debounce(func, delay) {
  return function(args) {
    var _this = this
    var _args = args
    clearTimeout(func.id)
    func.id = setTimeout(function() {
      func.call(_this, _args)
    }, delay)
 }
}

节流

  • 节流(throttle):设定一个时间间隔,某个频繁触发的函数,在这个时间间隔内只会执行一次。也就是说,这个频繁触发的函数会以一个固定的周期执行。

  • 应用场景:
    1.DOM 元素的拖拽功能实现(mousemove)
    2.监听滚动事件判断是否到页面底部自动加载更多()
    3.射击游戏的 mousedown/keydown 事件
    4.计算鼠标移动的距离(mousemove)

function throttle(func, delay) {
  let flag = true // 第一次是否立即执行,不用等待延迟
  return function() {
    var _this = this
    var _args = arguments
    if(flag) {
      func.apply(_this, _args)
      return flag = false
    }
    // 如果有func.id说明上一次还没执行完,不往下执行
   if(func.id) return false 
    func.id = setTimeout(function() {
        clearTimeout(func.id)
        // clearTimeout后还要销毁变量
        func.id = null
        func.apply(_this, _args)
      }, delay)
  }
}

参考有来自

@gdutwyg gdutwyg added the js label Jul 27, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant