文章参考
http://www.cnblogs.com/LuckyWinty/p/5949970.html
https://segmentfault.com/a/1190000002764479
什么是函数节流
个人理解:浏览器某个事件触发的平率非常高(例如onscroll事件),如果每次都去执行处理事件的逻辑,消耗大量的CPU资源导致浏览器卡死,因此需要在一段时间内只执行最后一次函数的函数叫做函数节流。
案例一:超过指定时间范围内执行一次
n=0; function resizehandler(){ console.log(new Date().getTime()); console.log(++n); } function throttle(method,context){ clearTimeout(method.tId); method.tId=setTimeout(function(){ method.call(context); },500); } window.onresize=function(){ throttle(resizehandler,window); };
案例二:在指定范围一定执行一次
n=0; function resizehandler(){ console.log(new Date().getTime()); console.log(++n); } function throttle(method ,delay, duration){ var timer = null; var begin = new Date(); return function(){ var context = this; var args = arguments; var current = new Date(); clearTimeout(timer); if(current-begin>=duration){ method.apply(context,args); begin=current; }else{ timer=setTimeout(function(){ method.apply(context,args); },delay); } } } window.onresize=throttle(resizehandler,100,500);