JS 函数节流 && 防抖

节流

节流是将多次执行变成每隔一段时间执行。

场景: 在监听页面滚动的时候滚轮滚动一下会连续执行n多次回调函数,这样造成性能的损耗, 使用节流能够非常好的节省性能的损耗。
eg:
未使用节流 window.onscroll = function(){ console.log("scrolling")};


1_no.png

//鼠标滚一下,连续触发了13次。。

使用节流函数 window.onscroll = throttle(function(){ console.log("scrolling")}, 100);


1_yes.png

//鼠标滚一下,只触发了一次

节流函数的简单实现

function throttle(fn, delay){
  if(typeof fn !== "function"){
    return new Error("argument[0] is not a function")
  }
  let context = this;
  let timer = null;
  return function(...args){
    if(!timer){
      timer = setTimeout(() => {
        fn.apply(context, args);
        timer = null;
      }, delay)
    }
  }
}

防抖

防抖是将连续触发改变为直到最后一次且等待时间超过设定时间在执行,期间都会重新计时;

场景: 在输入input输入联想的时候,不使用防抖则会不停的发送ajax请求,造成资源浪费。

防抖简单实现

function debounce(fn, delay) {
    if(typeof fn !== "function"){
        return new Error("argument[0] is not a function");
    }
    let context = this;
    let now = Date.now();
    let timer = null;
    return function(...args){
        let remain = Date.now() - now;
        //如果连续操作时间小于delay的时间则清空定时器,继续重新设定
        if(remain < delay){
            clearTimeout(timer);
            timer = null;
            now = Date.now();
            timer = setTimeout(() => {
                fn.apply(context, args);
            }, delay)
        }
    }
}

//完整代码
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>防抖</title>
</head>
<body>
    <input type="text" id="ipt" />
      <script>
        function debounce(fn, delay) {
          if (typeof fn !== "function") {
            return new Error("argument[0] is not a function");
          }
          let context = this;
          let now = Date.now();
          let timer = null;
          return function (...args) {
            let remain = Date.now() - now;
            //如果连续操作时间小于delay的时间则清空定时器,继续重新设定
            if (remain < delay) {
                clearTimeout(timer);
                timer = null;
                now = Date.now();
                timer = setTimeout(() => {
                    fn.apply(context, args);
                }, delay)
            }
        }
      }
      document.getElementById("ipt").addEventListener("input", debounce((e) => {
        console.log(e.target.value)
      }, 1000))
    </script>
  </body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在前端开发中有一部分的用户行为会频繁的触发事件执行,而对于DOM操作、资源加载等耗费性能的处理,很可能导致界面卡顿...
    bestvist阅读 529评论 0 5
  • 函数节流:一定时间内控制函数只能执行一次。函数不可高频率执行应用场景onscroll 函数防抖:是指频繁触发的情况...
    职场丧尸阅读 382评论 0 0
  • 前言 最近和前端的小伙伴们,在讨论面试题的时候。谈到了函数防抖和函数节流的应用场景和原理。于是,想深入研究一下两者...
    youthcity阅读 23,613评论 5 78
  • 函数节流 还记得上篇文章中说到的图片懒加载吗?我们在文章的最后实现了一个页面滚动时按需加载图片的方式,即在触发滚动...
    柏丘君阅读 2,863评论 1 19
  • 在日常开发中,我们经常能够碰到以下工作场景: 对提交按钮进行变态的点击压力测试输入框内容的实时校验(譬如验证用户名...
    叫我小徐阅读 1,017评论 0 5