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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • python处理亿级大数据(rar暴力破解器安卓版)

    转载请注明出处:https://blog.csdn.net/l1028386804/article/details/85566045今天是2019年元旦,首先祝大家元旦快乐,在这个喜庆的日子里,不知道大家有没有坚持研究自己所在领域的知识。其实,每项知识、技能的积累,需要的是日复一日的坚持,正所谓——持之以恒,贵在坚持,这样才能做到每天进步一点点。好了,步入正题,今天,闲来无事,基于Python…

    2022年4月15日
    51
  • pytest重试_arcmap重分类失败

    pytest重试_arcmap重分类失败安装:pip3installpytest-rerunfailures重新运行所有失败用例要重新运行所有测试失败的用例,请使用–reruns命令行选项,并指定要运行测试的最大次数:$py

    2022年7月28日
    4
  • html+css实现登录界面

    html+css实现登录界面

    2021年12月16日
    48
  • 频谱仪无线信号测试_无线信号检测仪app

    频谱仪无线信号测试_无线信号检测仪appAirMagnetSpectrumXT可实时探测并确定大量非WLAN干扰源,该干扰源会干扰和降低WLAN网络性能。设备或干扰源名单包括蓝牙设备、数字和模拟无绳电话、传统和变频微波炉、无线游戏控制器、数字视频转换器、婴儿监视器、RF干扰发射台、雷达、运动探测器和zigbee设备等等。用户也可获得干扰源的详细信息,包括峰值和平均功率、首次和最后看到的时间、中心频率、受影响的信道、干…

    2022年8月11日
    6
  • java从入门到精通_学习Java最好的10本书,从入门到精通

    java从入门到精通_学习Java最好的10本书,从入门到精通在当代,学习Java等编程课程的主要方式是视频资源。如果你想学,在网上五分钟之内就可以找到一堆学习视频,瞬间将你的硬盘填满。但是这些课程质量良莠不齐,对于小白来说,的确让人头痛不已。但是,书籍不同。对于书籍而言,它们都是出自业内大牛和资深的大学教授的精心编写,内容好坏与否,有很多同领域的网友都能帮你把关。所以说,如果你选对了学习的书籍,就可以不用担心自己在编程中,埋下错误的种子,同时还可以更深入的…

    2022年7月8日
    16
  • spring starter(怎么编写自己的starter)

    微服务架构从本质上说其实就是分布式架构,与其说是一种新架构,不如说是一种微服务架构风格。简单来说,微服务架构风格是要开发一种由多个小服务组成的应用。每个服务运行于独立的进程,并且采用轻量级交互。多数情况下是一个HTTP的资源API。这些服务具备独立业务能力并可以通过自动化部署方式独立部署。这种风格使最小化集中管理,从而可以使用多种不同的编程语言和数据存储技术。对于微服务架构系统,由于其服务粒度…

    2022年4月10日
    57

发表回复

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

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