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;                        }                    });                }            };        }]);

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

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

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Android Studio下载、安装和配置+SDK+tools下载(无敌超级详细版本)

    Android Studio下载、安装和配置+SDK+tools下载(无敌超级详细版本)下载:AndersonStudio是Google为Android提供的官方IDE工具,下载地址:http://www.android-studio.org/安装环境要求:其中JDK的最低版本是1.7,所以系统空闲内存至少2GB。如果你要安装andriod8.0左右的版本,最好内存能有8GB。AndroidStudio安装过程:以android-studio-id…

    2022年6月26日
  • 阿里云配置二级域名

    阿里云配置二级域名阿里云配置二级域名打开https://www.aliyun.com/?utm_content=se_1000301881打开控制台找到域名列表—解析—添加记录记录类型A-主机记录:yy.xxx.cn//—-yy二级域名xxx一级域名解析线路:默认记录值:39.xx….

    2022年5月21日
  • 如何设置电信光猫?图解手把手教你(超级详细)「建议收藏」

    如何设置电信光猫?图解手把手教你(超级详细)「建议收藏」自从电信升级成光纤之后,光猫经常有点小问题的,如果电信说帮你设置好漫天要价的话,求人还不如求自己,或者电信送的光猫坏了,买他们的超贵,自己买一个又好又便宜的自己设置就的了注意:2016年以后,电信为

    2022年8月3日
  • dhcp snooping option 82_dhcpsnooping的原理配置案例

    dhcp snooping option 82_dhcpsnooping的原理配置案例DHCPSnooping-option82relay的原理及实例一、采用DHCP服务的常见问题架设DHCP服务器可以为客户端自动分配IP地址、掩码、默认网关、DNS服务器等网络参数,简化了网络配置,提高了管理效率。但在DHCP服务的管理上存在一些问题,常见的有:●DHCPServer的冒充●DHCPServer的DOS,如DHCP耗竭●某些用户随便指定IP地址,造成IP地址冲突1、D…

    2022年10月15日
  • java swing视频教程下载_JAVA Swing 教程

    java swing视频教程下载_JAVA Swing 教程JAVASwing教程,包含所有练习源码和讲解教程!初级界面篇练习01分解颜色练习02画板练习03帧练习04画布练习05密码验证界面练习06对话框练习07滚动条练习08边框练习09单选框图片浏览器练习10卡片布局管理器练习11边界布局管理器练习12进程条练习13列表框和组合框练习14选项卡练习15菜单练习16菜单快捷键练习17模式对话框练习18网格布局管理器练习19复选框练习20单选框练习21…

    2022年9月5日
  • IDEA 将项目打包war包[通俗易懂]

    IDEA 将项目打包war包[通俗易懂]IntelliJIDEA将项目打包war包1、准备工作IntelliJIDEA开发工具可以正常运行的Java项目2、打包war包流程使用快捷键Ctrl+Alt+Shift+s或者鼠标点击选中项目名按F4打开ProjectStructure界面选择Artifacts,点击右边+,依次选择WebApplication:Archive和For’myP…

    2022年11月2日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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