实现函数节流和防抖封装。

函数节流和函数防抖

防抖: 首次点击会立即触发,重复触发点击不会触发,停止后会触发。(个人设计)
节流: 使连续执行的事件或函数,变为固定时间间隔执行

	/**
	 * 节制函数
	 * @param {Function} method 需要节制的函数
	 * @param {Number} delay  间隔时间
	 * @param {Number} duration 超出时间
	 * @param {Boolean} controlType 1防抖 0节流 默认0
	 * @return Function 
	 */
	function control(method, delay, duration, controlType) {
	    let timer = null;
	    let flag = false;
	    let start = new Date().getTime();
	    return function () {
	        let context = this;
	        let args = arguments;
	        if (controlType) {
	            if (!flag) {
	                method.apply(context, args);
	                flag = true;
	                start = new Date().getTime();
	            }
	            if (timer) clearTimeout(timer)
	            timer = setTimeout(function () {
	                flag = false;
	                let end = new Date().getTime();
	                if (end - start >= duration) {
	                    method.apply(context, args);
	                    start = end;
	                }
	            }, delay)
	        } else {
	            let end = new Date().getTime();
	            if (timer) clearTimeout(timer)
	            if (end - start >= duration) {
	                method.apply(context, args);
	                start = end;
	            } else {
	                timer = setTimeout(function () {
	                    method.apply(context, args);
	                    start = new Date().getTime();
	                }, delay)
	            }
	        }
	    }
	}
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在AngularJS中,你可以使用自定义指令或服务来实现防抖节流函数。下是一个示例: 1. 创建一个自指令或服务,例如名为`debThrottle`的自定义指令: ```javascript app.directive('debounceThrottle', function($timeout) { return { restrict: 'A', scope: { debounceThrottle: '&', debounceDelay: '=', throttleDelay: '=' }, link: function(scope, element) { var timeoutId; element.on('input', function() { if (timeoutId) { $timeout.cancel(timeoutId); } if (scope.debounceDelay) { timeoutId = $timeout(function() { scope.debounceThrottle(); }, scope.debounceDelay); } else if (scope.throttleDelay) { timeoutId = $timeout(function() { scope.debounceThrottle(); timeoutId = undefined; }, scope.throttleDelay); } else { scope.debounceThrottle(); } }); } }; }); ``` 2. 在你的HTML中使用该自定义指令,并传递相应的参数: ```html <input type="text" debounce-throttle="handleInput()" debounce-delay="500" throttle-delay="1000"> ``` 在上述示例中,我们通过`debounce-delay`和`throttle-delay`属性分别设置了防抖节流的延迟时间(以毫秒为单位)。 3. 在你的AngularJS控制器中,实现相应的处理函数: ```javascript $scope.handleInput = function() { // 处理输入事件 }; ``` 这样,当用户在输入框中输入时,`handleInput()`函数将根据防抖节流的设置进行触发。 通过自定义指令或服务的方式,你可以在AngularJS中方便地封装防抖节流函数,并在需要的地方进行复用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值