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)
上一篇 2022年6月20日 上午8:16
下一篇 2022年6月20日 上午8:36


相关推荐

  • 7-5 计算阶乘和 对于给定的正整数N,需要你计算 S=1!+2!+3!+…+N!。[通俗易懂]

    7-5 计算阶乘和 对于给定的正整数N,需要你计算 S=1!+2!+3!+…+N!。[通俗易懂]7-5 计算阶乘和 对于给定的正整数N,需要你计算 S=1!+2!+3!+…+N!。输入格式: 输入在一行中给出一个不超过10的正整数N。输出格式: 在一行中输出S的值。 输入样例: 3 输出样例: 9#include<iostream>using namespace std;int J(int n){ int jie=1; for (int i…

    2022年8月18日
    6
  • pageoffice集成

    pageoffice集成pageOffice 集成简述 下列简述是跨域请求 将文件服务器中的文件下载到本地 然后打开 保存之后再次上传到服务器 1 下载试用版本项目文件 Samples4 是 pageOffice 测试项目包 直接可在 TomcatWebApp 中运行 访问 localhost 8080 Samples4 index html 即可访问到 p

    2026年3月18日
    2
  • 编程必备,程序员应该都知道的7款文本编辑器

    编程必备,程序员应该都知道的7款文本编辑器

    2022年3月2日
    52
  • 【小程序】关于bindtap传值

    【小程序】关于bindtap传值啦啦啦 端正态度 开始写技术博客哼哼 刚开始练手 准备模仿朝夕日历的番茄闹钟进行语法以及布局练习 从最简单的需求开始 点击分类 下面多一条红色 border 表示选中 在 Page 中定义一个值 tagsSelect 作为选项的参数 Page data tagsSelect 0 定义一个方法 来接收选项值的改变 从而改变样式 但如果你这么写 vie

    2026年3月17日
    2
  • datagrip 2.4 激活_最新在线免费激活

    (datagrip 2.4 激活)JetBrains旗下有多款编译器工具(如:IntelliJ、WebStorm、PyCharm等)在各编程领域几乎都占据了垄断地位。建立在开源IntelliJ平台之上,过去15年以来,JetBrains一直在不断发展和完善这个平台。这个平台可以针对您的开发工作流进行微调并且能够提供…

    2022年3月29日
    132
  • disqualification游戏_ACWING怎么样

    disqualification游戏_ACWING怎么样如下图所示,有一个 # 形的棋盘,上面有 1,2,3 三种数字各 8 个。给定 8 种操作,分别为图中的 A∼H。这些操作会按照图中字母和箭头所指明的方向,把一条长为 7 的序列循环移动 1 个单位。例如下图最左边的 # 形棋盘执行操作 A 后,会变为下图中间的 # 形棋盘,再执行操作 C 后会变成下图最右边的 # 形棋盘。给定一个初始状态,请使用最少的操作次数,使 # 形棋盘最中间的 8 个格子里的数字相同。输入格式输入包含多组测试用例。每个测试用例占一行,包含 24 个数字,表示将初始棋

    2022年8月8日
    8

发表回复

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

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