美文网首页
js防抖节流应用场景及写法

js防抖节流应用场景及写法

作者: yxb10com | 来源:发表于2020-06-06 01:56 被阅读0次

应用场景:

防抖:

1.search搜索联想,用户在不断输入值时,用防抖来节约ajax请求。
2.滚动条滚动的时候触发事件

//防抖实例

//ajax请求
function ajax(content) {
           console.log(content)
          console.log('ajax request ' + content)
        }
//利用闭包将timer存在自己得作用域
function debounce(fun, delay) { 

          let timer = null;

          return function (args) {
              let that = this
              let _args = args
              clearTimeout(timer)
              timer = setTimeout(function () {
                  fun.call(that, _args)
              }, delay)
          }
        }
//生成闭包
let debounceAjax = debounce(ajax, 3000)

//输入框change事件
function inputChange(e) {
  debounceAjax(e.target.value)
}

节流:

1.鼠标不断点击触发,mousedown(单位时间内只触发一次)
2.上拉触底加载更多

//节流实例

//ajax请求
function click(content) {
    console.log('点击了参数是:' + content)
        }
//利用闭包将timer存在自己得作用域
function debounce(fun, delay) { 

          let can = false;

          return function (args) {
              let that = this
              let _args = args
              if(can) return
              can = true
              timer = setTimeout(function () {
                  fun.call(that, _args)
                  can = false
              }, delay)
          }
        }
//生成闭包
let debounceAjax = debounce(ajax, 3000)

//鼠标点击事件
function onClick(e) {
  debounceAjax(e.target.value)
}

相关文章

网友评论

      本文标题:js防抖节流应用场景及写法

      本文链接:https://www.haomeiwen.com/subject/rnkvzhtx.html