函数防抖与函数节流

作用: 节省浏览器CPU资源

函数防抖

  应用场景:用户输入手机号完毕后再进行验证。

 1 var timer = null;
 2 document.getElementById("phoneNum").addEventListener('keyup', function(){
 3      clearTimeout(timer);
 4      var val = this.value;
 5      timer = setTimeout(function(){
 6          if(val.length !== 11){
 7                alert('手机号格式错误!');
 8          }else{
 9                console.log('success !');
10          }
11      }, 1000);
12 });

函数节流

  应用场景:监听页面元素滚动事件

 1 var canRun = true;
 2 document.getElementById("throttle").onscroll = function(){
 3     if(!canRun){
 4         // 判断是否已空闲,如果在执行中,则直接return
 5         return;
 6     }
 7 
 8     canRun = false;
 9     setTimeout(function(){
10         console.log("函数节流");
11         canRun = true;
12     }, 300);
13 };
原文地址:https://www.cnblogs.com/lvshaonan/p/8622542.html