zoukankan      html  css  js  c++  java
  • 所谓的防抖节流函数

    // 防抖 函数
    // 函数防抖(debounce):触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。
    export const debounce = (fn, delay = 300)=> {   //默认300毫秒
        var timer;
        return function() {
            var args = arguments;
            if(timer) {
                clearTimeout(timer);
            }
            timer = setTimeout(() => {
                fn.apply(this, args);   // 改变 this
            }, delay);
        };
    }
    
    // 节流
    // 函数节流(throttle):高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率。
    export const throttle = (fn, delay, mustRun) => {
    	var timer = null, previous = null;
    	return function () {
    		var now = +new Date(), context = this, args = arguments;
                    //过去的时间不存在的时候 将现在的时间赋值
    		if (!previous ) previous = now;
                    //获取时间差
    		var remaining = now - previous;
    		if (mustRun && remaining >= mustRun) {
    			fn.apply(context, args);
    			previous = now;
    		} else {
    			clearTimeout(timer);
    			timer = setTimeout(function () {
    				fn.apply(context, args);
    			}, delay);
    		}
    	}
    }
    
    愿以往所学皆有所获
  • 相关阅读:
    Oracle表级约束和列级约束
    什么是SSL证书服务?
    什么是阿里云SCDN
    什么是阿里云CDN
    什么是弹性公网IP?
    什么是云解析DNS?
    什么是DataV数据可视化
    什么是大数据计算服务MaxCompute
    什么是文件存储NAS
    什么是云存储网关
  • 原文地址:https://www.cnblogs.com/Azune/p/13234272.html
Copyright © 2011-2022 走看看