美文网首页
节流 / 防抖

节流 / 防抖

作者: 小马哒哒哒哒哒哒 | 来源:发表于2020-04-10 17:16 被阅读0次

    使用场景

    • debounce
      • search搜索联想,用户在不断输入值时,用防抖来节约请求资源。
      • 频繁操作点赞和取消点赞,因此需要获取最后一次操作结果并发送给服务器
    • throttle
      • 鼠标不断点击触发,mousedown(单位时间内只触发一次)
      • indow触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次

    函数

    // 防抖
      debounce(fn, wait=1000) {
        let timeout;
        return () => {
          clearTimeout(timeout)
          timeout = setTimeout(() => {
            fn.call(this, arguments);
          }, wait)
        }
      }
    
    //节流
    throttle(fn, wait=1000) {
        let canRun = true;
        return () => {
            if (!canRun) return;
            canRun = false;
            setTimeout(() => {
                fn.apply(this, arguments);
                canRun = true;
            }, wait);
        };
    }
    

    在Vue中用法

    searchInputCallback:tool.debounce(()=>{
      console.log('sss')
    })
    

    相关文章

      网友评论

          本文标题:节流 / 防抖

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