zoukankan      html  css  js  c++  java
  • js 防抖与节流原理

    防抖和节流是前端应用开发中常见的两个功能,其原理都是利用闭包,缓存延迟时间。常用于窗口的resize、scroll,输入框内容校验等操作。

    (1)防抖,思路:在规定时间内未触发第二次,则执行,代码如下

    function debounce(fn, delay) {

      let time = null ; //定时器

      delay = delay || 500

      //利用闭包,缓存delay

      return function() {

        let arg = arguments

        if(time) {

          clearTimerOut(time)

        }

            time = setTimerOut(()=>{

          fn.apply(this,arg)

        },delay)

      }

    }

    (2)节流,当持续触发事件时,保证一定时间段内只调用一次

      function throttle(fn,delay) {

        let pre = Date.now()

        deley = delay || 500;

        return function(){

          let nowT = Date.now()

          let arg = arguments

          if(nowT  - pre  > = delay ) {

            fn.apply(this ,arg)

            pre = Date.now()

          }

        }

        

      }

  • 相关阅读:
    python 函数嵌套
    python 函数对象
    python 函数参数
    python 连接MySQL报错及解决方案
    解决 No module named pip
    python 文件处理
    python
    python 元祖
    python 读取域名信息
    ubuntu 配置网卡,DNS, iptables
  • 原文地址:https://www.cnblogs.com/liuhp/p/12217129.html
Copyright © 2011-2022 走看看