JS节流与防抖

节流

节流,走字面上理解就是节约流量。比作水就话就是让水流的少一点,节约一点。对应到JS当中,就是在scroll事件和mousemove事件的时候,浏览器会很频繁的被触发,会导致对应的事件也会被很频繁的触发,这样就会使得浏览器资源消耗很大,此时就需要节流。

前面说过了,节流只是把水关小一点,同样,我们在JS中的节流就是让事件触发的不那么频繁。

        function throttle(func, ms = 1000) {
          let canRun = true
          return function (...args) {
            if (!canRun) return //如果是false 就终止
            canRun = false
            setTimeout(() => {
              func.apply(this, args) //将this指向指向为事件触发时的this
              canRun = true
            }, ms)
          }
        }
        
        // 测试
        const task = () => { console.log('run task') }
        const throttleTask = throttle(task, 1000)
        window.addEventListener('mousemove', throttleTask)

去抖

去抖,用淘宝页面举例子,当我们在搜索输入词汇时,他会根据词汇自动的去获取后台与之相关联的数据。但是如果在我们没输入一个字符时都去响应,这也响应的泰国频繁且响应的数据都是无效的。那么我们就需要用到去抖,即在判断用户是否还要输入,如果不输入了再去发起请求。

function debounce(func, ms = 1000) {
          let timer;
          return function (...args) {
            if (timer) { 
              clearTimeout(timer)
            }
            // console.log(timer)
            timer = setTimeout(() => {
              func.apply(this, args) //将this绑定为执行环境的this
            }, ms)
          }
        }
        // 测试
        const task = () => { console.log('run task') }
        const debounceTask = debounce(task, 1000)
        window.addEventListener('mousemove', debounceTask)

节流与防抖的区别就是,节流是多少秒执行一次,而防抖是只会执行一次。

原文地址:https://www.cnblogs.com/elink/p/13714929.html