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开发从零开始》视频全集「建议收藏」

    《Android开发从零开始》视频全集「建议收藏」这套教程是若水倾情为有一定Java基础的朋友制作的Android开发从零开始视频集合,目前共38集。《Android开发从零开始》文章列表:1.Android开发环境的搭建2.模拟器的使用3.第一个Android程序4.TextView控件学习5.EditText控件学习6.DDMS视图&Button7.Intent初级学习8

    2022年5月9日
    37
  • armeabi-v7a架构(sv7a)

    在ANE中如果SDK调用了so库,则需要把so库放到ANE下Android-ARM/lib/armeabi(调试模式)或者armeabi-v7a(发行模式)下。可以贴个ADT代码说明问题://m_configType.equals(“apk”)是否是发行模式//(hasCaptiveRuntime()是否带运行时if((m_configType.equals(“apk”

    2022年4月13日
    67
  • 免费下载电子书攻略大全_我被系统攻略了txt

    免费下载电子书攻略大全_我被系统攻略了txt经常帮博友们查找各种书籍,也算是攒了一些经验。在此整理下我是如何找电子书籍的,准确来说,是找书籍的网站汇总。本文借鉴了@陆浑戎,@设定控@没有我找不到的电子书等朋友的方法,在此表示感谢! 如以下内容有不当之处,还请各位指正。一、初级攻略利用网盘检索工具进行检索在此推荐几个我常用的网盘检索工具:1、西林街西林街::网盘搜索引擎,更是网盘搜索神器!

    2022年8月10日
    6
  • mybatis 批量插入「建议收藏」

    开发项目中,总是与数据打交道,有的时候将数据放入到一个集合中,然后在遍历集合一条一条的插入,感觉效率超不好,最近又碰到这个问题,插入50条数据用了将近1s,完全满足不了系统的需求.效率必须加快,然后网上查询资料,历经千万bug,终于搞定,这里指提供mybatis中的配置,至于dao层的调用mybatis就自己上网查询下资料吧1根据网上搜了一下资料,在sql-mapper.xml文件中写了如下配

    2022年4月9日
    33
  • oracle中的varchar2存储中文,varchar2存储汉字

    oracle中的varchar2存储中文,varchar2存储汉字NVARCHAR2和VARCHAR2的区别,从使用角度来看区别在于:NVARCHAR2在计算长度时和字符集相关,例如数据库是中文字符集时,以长度10为例,则NVARCHAR2(10)可以存进去10个汉字,如果用来存英文也只能存10个字符。VARCHAR2(10)只能存进5个汉字,英文则可以存10个。********************************************…

    2022年6月16日
    23
  • MyBatis学习总结(5)——实现关联表查询

    MyBatis学习总结(5)——实现关联表查询

    2021年7月8日
    91

发表回复

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

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