• JavaScript-函数防抖与函数节流


    函数防抖与函数节流

    函数防抖和函数节流是JavaScript在处理高频事件时的一种处理手段。

    函数防抖

    函数防抖:把「多个信号」转化为「单个信号」,在Javascript中,如果一个事件频繁发生,事件在触发后过一段事件才执行,但是如果在这一段时间内,我们又触发了这个事件,则会重新计时。

    应用场景:inputsubmit

    function debounce (fn, delay){
        let timer = null;
        return function () {
            timer && clearTimeout(timer);
            let self = this, args = arguments;
            timer = setTimeout(function () {
                fn.apply(self, args);
            }, delay || 1000);
        }
    }
    

    函数节流

    函数节流:函数节流是一定事件内如果多次触发事件只执行一次回调函数。(如果事件一直触发就相当于每隔一定时间执行一次回调)

    应用场景:mousemoveresize

    function throttle(fn, delay) {
        let flag = true, timer = null;
        return function () {
            if (!flag) return;
            flag = false;
            let self = this, args = arguments;
            timer = setTimeout(function () {
                flag = true;
                fn.apply(self, args);
            }, delay || 500);
        };
    }
    
  • 相关阅读:
    计算机网络基础 汇总
    指针与数组
    卡特兰数
    Leetcode Sort Colors
    Leetcode Group Shifted Strings
    Leetcode Summary Ranges
    Leetcode Count Primes
    Leetcode Reverse Words in a String II
    Leetcode Reverse Words in a String
    Leetcode Rotate Array
  • 原文地址:https://www.cnblogs.com/luwenfeng/p/11693790.html
Copyright © 2020-2023  润新知