关于防抖和节流的一点应用

91 阅读1分钟

防抖

直接的防抖算法

 let inputDom = document.querySelector("input")
 let t = null
 inputDom.onput = () => {
   if (t!==null) {
     clearInternal(t);
   }
   t = setInternal(()=>{
     console.log(this.value)
     // 业务代码
   })
 }

利用闭包封装防抖算法

 
 <!DOCTYPE html>
 <html lang="en">
 ​
 <head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>防抖</title>
 </head>
 ​
 <body>
   <input type="text" placeholder="请输入学号">
   <script>
     let inputDom = document.querySelector("input")
 ​
     inputDom.oninput = debounce(function () {
       // 业务代码中this指向window对象
       console.log("业务代码的this: ", this)
       console.log(this.value)
       // 真实的业务代码业务代码
     }, 500)
     
     function debounce (fn, delayTime) {
       // console.log("debounce")
       let t = null
       // 内部函数使用了外部函数的变量
       return function () {
         if (t !== null) {
           clearTimeout(t)
         }
         t = setTimeout(() => {
           // 返回函数中this指向inputDom
           console.log("返回函数的this: ", this)
           // 使用call改变fn函数中的this指向, 使之也指向inputDom
           fn.call(this)
         }, delayTime)
       }
     }
   </script>
 </body>
 ​
 </html>

节流

下面是一段微信小程序业务中的真实代码, 通过最基本的节流操作减轻了服务器压力

当用户连续点击按钮时, 只在上一次请求服务器结束, 也就request结束后, 才能发起下一次请求

 var loadingCas = true  
 bindCas (e) {
     var that = this
     // 输入校验
     if (!this.data.stuId) {
       wx.showToast({
         title: '学号不能为空',
         icon: 'none',
         duration: 1500
       })
     } else if (!this.data.casPwd) {
       wx.showToast({
         title: '密码不能为空',
         icon: 'none',
         duration: 1500
       })
     } else if (this.data.isAgree == false) {
       wx.showToast({
         title: '需同意用户协议',
         icon: 'none',
         duration: 1500
       })
     } else {
       // 校验通过, 开始绑定
       wx.showLoading({
         title: '绑定中, 请稍等',
       })
       // 当loadingCas为true时才发起请求
       if (loadingCas) {
         loadingCas = false
         wx.request({
           url: "",
           method: 'POST',
           header: {
             'content-type': 'application/x-www-form-urlencoded'
           },
           data: {
             StuId: that.data.stuId,
             CasPwd: that.data.casPwd
           },
           success(res) {
             ...
           },
           fail(res) {
             ...
           },
           complete() {
             wx.hideLoading({})
             // 请求完成后修改loadingCas为true, 可以发起下一次请求
             loadingCas = true
           }
         })
       }else {
         wx.showToast({
           title: '请稍等',
         })
       }
     }
   },