zoukankan      html  css  js  c++  java
  • javaScript节流与防抖

    一、节流(throttle)

    用来实现阻止在短时间内重复多次触发同一个函数。主要用途:防止使用脚本循环触发网络请求的函数的恶意行为,确保请求的真实性(当然也包括其他阻止高频触发行为的应用);

    实现原理图:

     代码实现:

     1 //节流函数
     2 function throttle(handler,wait){
     3     var lastDate = 0;
     4     return function(){
     5         var newDate = new Date().getTime();
     6         if(newDate - lastDate > wait){
     7             handler.apply(this,arguments);
     8         }
     9         lastDate = newDate;
    10     }
    11 }

    节流函数测试:

    1 function foo(nub){
    2     console.log(nub);
    3 }
    4 var han = throttle(foo,1000); //设置节流时间为1000毫秒
    5 for(var i = 0; i < 100; i++){
    6     han("1");//使用for调用执行节流函数han只能第一次被触发,因为程序的执行速度是微秒级的速度
    7 }

    二、防抖

    用来实现高频触发函数调用时,实际只调用最后一次函数执行。主要用途:用于可能出现高频触发DOM结构或样式修改,导致的页面高频重排重绘,严重影响页面性能,同时也导致操作的DOM闪烁抖动的情况,造成体验效果差。(也包括其他阻止高频触发的用途)

    代码实现:

     1 //防抖函数
     2 function antishake(handler,interval){
     3     var lastDate = 0;
     4     var time ;
     5     return function(){
     6         var self = this;
     7         var args = arguments;
     8         clearTimeout(time);
     9         time = setTimeout(function(){
    10             handler.apply(self,args);
    11         },interval);
    12     }
    13 }

    防抖函数测试:

     1 <div id="nub">0</div>
     2 <button id="but">点我</button>
     3 <script>
     4     var odiv = document.getElementById("nub");
     5     var oBut = document.getElementById("but");
     6         oBut.onclick = antishake(fun,1000);//一秒以内的连续点击只会触发一次
     7     var num = 0;
     8     function fun(){
     9         odiv.innerText =  ++num;
    10     }        
    11 </script>    
  • 相关阅读:
    [JSOI2007][BZOJ1031] 字符加密Cipher|后缀数组
    leetcode Flatten Binary Tree to Linked List
    leetcode Pascal's Triangle
    leetcode Triangle
    leetcode Valid Palindrome
    leetcode Word Ladder
    leetcode Longest Consecutive Sequence
    leetcode Sum Root to Leaf Numbers
    leetcode Clone Graph
    leetcode Evaluate Reverse Polish Notation
  • 原文地址:https://www.cnblogs.com/ZheOneAndOnly/p/11515997.html
Copyright © 2011-2022 走看看