zoukankan      html  css  js  c++  java
  • 节流和防抖

    作用:减少调用频率,减轻浏览器负担,提高用户体验

    场景:

      函数防抖(debounce):当持续触发事件时,在一定时间(wait)内没有再次触发,则执行处理函数。若在期间有触发了事件,那么重当前时间开始重新计时。(搜索框)

      节流(throttle):一定时间段内只能触发一次处理函数

    函数防抖实现:

    function debounce(fn, wait) {
        var timeout = null;
        return function() {
            clearTimeout(timeout);
            timeout = setTimeout(fn, wait);
        }
    }
    // 处理函数
    function handle() {
        console.log(Math.random()); 
    }
    // 滚动事件
    window.addEventListener('scroll', debounce(handle, 1000));

    函数节流实现:

     
    定时器实现--第一次先等待再 执行
    var throttle = function(func, delay) {
                var timer = null;
                return function() {
                    var context = this;
                    var args = arguments;
                    if (!timer) {
                        timer = setTimeout(function() {
                            func.apply(context, args);
                            timer = null;
                        }, delay);
                    }
                }
            }
            function handle() {
                console.log(Math.random());
            }
            window.addEventListener('scroll', throttle(handle, 1000));
         2.时间戳实现---第一次先执行    
            function throttle(func,wait){
                var lastTime = 0;
                return function(){
                    var nowTime = +new Date();
                    if(nowTime -lastTime >wait){
                        func.apply(this,arguments);
                        lastTime = nowTime;
                    }
                }
            } 
  • 相关阅读:
    PAT 1038. 统计同成绩学生
    PAT 1037. 在霍格沃茨找零钱
    PAT 1036. 跟奥巴马一起编程
    PAT 1035. 插入与归并
    PAT 1034. 有理数四则运算
    PAT 1033.旧键盘打字
    [转载]信号处理基础知识——加窗windowing
    On the use of spectrogram function in matlab
    [转载]【MATLAB】pwelch函数的相关参数解释
    [转载]时频特性分析(Matlab)
  • 原文地址:https://www.cnblogs.com/freefy/p/12153978.html
Copyright © 2011-2022 走看看