js笔试题合集-持续更新中

1.实现防抖函数(debounce)

防抖函数原理:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。

//func 是事件触发要执行的事件
//delay 是延时多少时间
function onbounce(func, delay) {
  let times;
  let context = this; 
  return function () {
    let args = arguments;
    clearTimeout(times);
    times = setTimeout(function() {
      func.apply(context, args);  //改变this的指向 传递上下文参数
    },delay);
  }
}

//方法二
// 防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

简略例子 你可以粘到html里运行

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>防抖函数</title>
    </head>
    <!-- css -->
    <style>
        #box {
            margin: 50px auto;
            width: 60%;
            height: 200px;
            background-color: pink;
            cursor: pointer;
            text-align: center;
            line-height: 200px;
            color: #fff;
            font-size: 20px;
        }
    </style>
    <!-- html -->
    <body>
        <div id="box"></div>
    </body>
    <!-- js -->
    <script>
        window.onload = function() {
            var count = 1;
            var doc = document.getElementById('box');
            console.log(doc);

            function getUserAtion(e) {
                // console.log(e);
                doc.innerHTML = count ++;
            }

            function onbounce (func, wait) {
                var times;
                var context = this;
                return function(...args) {
                    clearTimeout(times);
                    times = setTimeout(function() {
                        func.apply(context,args);
                    },wait);
                }
            }

            doc.onmousemove = onbounce(getUserAtion, 2000);
        }
    </script>
</html> 

适用场景:

  • 按钮提交场景:防止多次提交按钮,只执行最后提交的一次
  • 服务端验证场景:表单验证需要服务端配合,只执行一段连续的输入事件的最后一次,还有搜索联想词功能类似

2.实现节流函数(throttle)

节流的原理很简单:如果你持续触发事件,每隔一段时间,只执行一次事件。
根据原理,实现方式有2种,一种是时间戳 一种是定时器

1.时间戳

使用时间戳,当触发事件的时候,我们取出当前的时间戳,然后减去之前的时间戳(最一开始值设为 0 ),如果大于设置的时间周期,就执行函数,然后更新时间戳为当前的时间戳,如果小于,就不执行。

function throlttle (func, wait) {
      var previous = 0;
      return (...args)=> {
           var now = +new Date();
           if(now - previous > wait) {
                func.apply(this, args);
                previous = now;
            }
      }
 }
2.定时器

当触发事件的时候,我们设置一个定时器,再触发事件的时候,如果定时器存在,就不执行,直到定时器执行,然后执行函数,清空定时器,这样就可以设置下个定时器。

function throlttle(func, wait) {
      var times;
      return (...args)=> {
          if(!times) {
                times = setTimeout(()=> {
                   times = null;
                   func.apply(this, args);
               },wait)
           }
      }
 }

适用场景:

  • 拖拽场景:固定时间内只执行一次,防止超高频次触发位置变动
  • 缩放场景:监控浏览器resize
  • 动画场景:避免短时间内多次触发动画引起性能问题
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。