angular debounce throttle「建议收藏」

angular debounce throttle「建议收藏」throttle我们这里说的throttle就是函数节流的意思。再说的通俗一点就是函数调用的频度控制器,是连续执行时间间隔控制。主要应用的场景比如:鼠标移动,mousemove事件DOM元素动态定位,window对象的resize和scroll事件有人形象的把上面说的事件形象的比喻成机关枪的扫射,throttle就是机关枪的扳机,你不放扳机,它就一直扫射。我们

大家好,又见面了,我是你们的朋友全栈君。

throttle

我们这里说的throttle就是函数节流的意思。再说的通俗一点就是函数调用的频度控制器,是连续执行时间间隔控制。主要应用的场景比如:

  • 鼠标移动,mousemove 事件
  • DOM 元素动态定位,window对象的resize和scroll 事件

有人形象的把上面说的事件形象的比喻成机关枪的扫射,throttle就是机关枪的扳机,你不放扳机,它就一直扫射。我们开发时用的上面这些事件也是一样,你不松开鼠标,它的事件就一直触发。回到window resize和scroll事件的基本优化提到的优化:

  1. var resizeTimer=null;
  2. $(window).on('resize',function(){
  3. if(resizeTimer){
  4. clearTimeout(resizeTimer)
  5. }
  6. resizeTimer=setTimeout(function(){
  7. console.log("window resize");
  8. },400);
  9. }
  10. );

setTimeout和clearTimeout其实就是一个简单的 throttle,很多好的控制了resize事件的调用频度。

debounce

debounce和throttle很像,debounce是空闲时间必须大于或等于 一定值的时候,才会执行调用方法。debounce是空闲时间的间隔控制。比如我们做autocomplete,这时需要我们很好的控制输入文字时调用方法时间间隔。一般时第一个输入的字符马上开始调用,根据一定的时间间隔重复调用执行的方法。对于变态的输入,比如按住某一个建不放的时候特别有用。

debounce主要应用的场景比如:

  • 文本输入keydown 事件,keyup 事件,例如做autocomplete

这类网上的方法有很多,比如Underscore.js就对throttle和debounce进行封装

angular 1.3版本之后可以使用 ngModelOptions参数在设置相应的debounce

ngModelOptions Object

options to apply to the current model. Valid keys are:

  • updateOn: string specifying which event should the input be bound to. You can set several events using an space delimited list. There is a special event called default that matches the default events belonging of the control.
  • debounce: integer value which contains the debounce model update value in milliseconds. A value of 0 triggers an immediate update. If an object is supplied instead, you can specify a custom value for each event. For example:ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"
  • allowInvalid: boolean value which indicates that the model can be set with values that did not validate correctly instead of the default behavior of setting the model to undefined.
  • getterSetter: boolean value which determines whether or not to treat functions bound tongModel as getters/setters.
  • timezone: Defines the timezone to be used to read/write the Date instance in the model for<input type="date"><input type="time">, … . It understands UTC/GMT and the continental US time zone abbreviations, but for general use, use a time zone offset, for example, '+0430' (4 hours, 30 minutes east of the Greenwich meridian) If not specified, the timezone of the browser will be used.

1.2版本之前的可以自行进行封装:

angular.module('lz.utils.debounce', [])        .service('$debounce', ['$timeout', function ($timeout) {            return function (func, wait, immediate, invokeApply) {                var timeout, args, me, result;                function debounce() {                    /* jshint validthis:true */                    me = this;                    args = arguments;                    var later = function () {                        timeout = null;                        if (!immediate) {                            result = func.apply(me, args);                        }                    };                    var callNow = immediate && !timeout;                    if (timeout) {                        $timeout.cancel(timeout);                    }                    timeout = $timeout(later, wait, invokeApply);                    if (callNow) {                        result = func.apply(me, args);                    }                    return result;                }                debounce.cancel = function () {                    $timeout.cancel(timeout);                    timeout = null;                };                return debounce;            };        }])    /**     * usage: <XX lz-debounce="500" immediate="true" ng-model="test"></XX>     */        .directive('lzDebounce', ['$debounce', '$parse', function (debounce, $parse) {            return {                require: 'ngModel',                priority: 999,                link: function ($scope, $element, $attrs, ngModelController) {                    var debounceDuration = $parse($attrs.debounce)($scope);                    var immediate = !!$parse($attrs.immediate)($scope);                    var debouncedValue, pass;                    var prevRender = ngModelController.$render.bind(ngModelController);                    var commitSoon = debounce(function (viewValue) {                        pass = true;                        ngModelController.$$lastCommittedViewValue = debouncedValue;                        ngModelController.$setViewValue(viewValue);                        pass = false;                    }, parseInt(debounceDuration, 10), immediate);                    ngModelController.$render = function () {                        prevRender();                        commitSoon.cancel();                        //we must be first parser for this to work properly,                        //so we have priority 999 so that we unshift into parsers last                        debouncedValue = this.$viewValue;                    };                    ngModelController.$parsers.unshift(function (value) {                        if (pass) {                            debouncedValue = value;                            return value;                        } else {                            commitSoon(ngModelController.$viewValue);                            return debouncedValue;                        }                    });                }            };        }]);

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/151552.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • C# FileStream简单介绍和使用

    C# FileStream简单介绍和使用本章讲述:FileStream类的基本功能,以及简单示例;1、引用命名空间:usingSystem.IO;2、注意:使用IO操作文件时,要注意流关闭和释放问题!强力推荐:将创建文件流对象的过程写在using当中,会自动帮助我们释放资源;使用try{}catch(Exceptionex){}进行一次捕获;3、FileStream操作字节,可以操作任何类型…

  • python+selenium环境搭建_pycharm配置anaconda环境

    python+selenium环境搭建_pycharm配置anaconda环境最近在研究python+selenium进行自动化测试。然后用的python开发工具是Pycharm。然后,今天就跟大家讲一下怎么搭建一整套的自动化测试环境。安装python首先,安装python。python可以在官网下载。安装可参考链接:http://blog.csdn.net/florachy/article/details/72769813我安装的是python3.6.0:…

  • 经典算法–约瑟夫环问题的三种解法

    经典算法–约瑟夫环问题的三种解法约瑟夫环问题,这是一个很经典算法,处理的关键是:伪链表问题描述:N个人围成一圈,从第一个人开始报数,报到m的人出圈,剩下的人继续从1开始报数,报到m的人出圈;如此往复,直到所有人出圈。(模拟此过程,输出出圈的人的序号)在数据结构与算法书上,这个是用链表解决的。我感觉链表使用起来很麻烦,并且这个用链表处理起来也不是最佳的。我画了一个图用来理解:有如下问题需要首先考虑:1、“圈…

  • 使用jprobe建设镜面层叠的原则和见解

    使用jprobe建设镜面层叠的原则和见解

  • embedded dylibs/frameworks are only supported on iOS 8.0 and later 错误解决[通俗易懂]

    embedded dylibs/frameworks are only supported on iOS 8.0 and later 错误解决

  • MySQL时间戳转日期

    MySQL时间戳转日期使用FROM_UNIXTIME函数,具体如下:FROM_UNIXTIME(unix_timestamp,format)返回表示Unix时间标记的一个字符串,根据format字符串格式化。format可以包含与DATE_FORMAT()函数列出的条目同样的修饰符。下列修饰符可以被用在format字符串中:%M月名字(January……December)%W星期名字(Sunda

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号