美文网首页
节流防抖

节流防抖

作者: 酒暖花深Q | 来源:发表于2021-04-22 10:39 被阅读0次

函数防抖

在事件被触发n 秒后在执行回调,如果在这n秒事件又被触发,则重新计时

函数节流

规定一个时间单位,在这个时间单位内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只能一次性生效

函数防抖的实现

function debounce(fn, wait) {
      const timer = null;
      return function() {
        const context = this;
        args = arguments;
        // 如果此时存在定时器,则取消之前的定时器重新计时
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        // 设置定时器,使事件间隔指定事件后执行
        timer = setTimeout(() => {
          fn.apply(context, args);
        }, wait)
      }
    }

函数节流的实现

function throttle(fn, delay) {
      const  content = this;
      args = arguments;
      const nowTime = Date.noew();
      
      // 如果两次时间间隔超过了指定时间则执行函数
      if(nowTime - preTime >= delay) {
        const preTime = Date.now();
        return fn.apply(content, args);
      }
    }

相关文章

网友评论

      本文标题:节流防抖

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