• JS的防抖与节流学习笔记


    防抖(debounce):当持续触发事件时,在一定的时间段内,只有最后一次触发的事件才会执行。

    例:

        function debounce(fn, wait) {
            var timer = null;
            return function() {
                if(timer !== null) {
                    clearTimeout(timer);
                }
                timer = setTimeout(fn, wait);  
            }
        }
        function handle() {
            console.log('防抖处理!'); 
        }
        window.addEventListener('scroll', debounce(handle, 1000));

    节流(throttle):当持续触发事件时,已执行的事件在一定时间段内不会再次执行。实现节流有时间戳和定时器两种方式。

    例:

    // 时间戳:
        var throttle = function(func, delay) {
            var prev = Date.now();
            return function() {
                var now = Date.now();
                if (now - prev >= delay) {
                    func();
                    prev = Date.now();
                }
            }
        }
        function handle() {
            console.log('节流处理!');
        }
        window.addEventListener('scroll', throttle(handle, 1000));
    // 定时器:
        var throttle = function(func, delay) {
            var timer = null;
            return function() {
                if (!timer) {
                    timer = setTimeout(function() {
                        func();
                        timer = null;
                    }, delay);
                }
            }
        }
        function handle() {
            console.log('节流处理!');
        }
        window.addEventListener('scroll', throttle(handle, 1000));

    函数防抖和节流都是防止某一事件被频繁触发;区别:防抖是将多次执行变为最后一次执行,节流是将多次执行变为一段时间只执行一次


    应用场景:窗口resize、页面scroll、拖拽、限时抢购、实时搜索等。

  • 相关阅读:
    02.jwt单点登录
    04.RBAC
    COM interop
    C++、c#互调用之VC6 调用 VC6 COM
    Type Library Importer (Tlbimp.exe)
    C++、C#互调用之C++ 调用C# dll
    VS tools
    Type Library to Assembly 转换摘要
    7个顶级心理预言
    c++、C#互调用之c# 调用 vc6 COM
  • 原文地址:https://www.cnblogs.com/fengyuexuan/p/11607756.html
Copyright © 2020-2023  润新知