防抖和节流的做用都是防止函数屡次调用。区别在于,假设一个用户一直触发这个函数,且每次触发函数的间隔小于wait,防抖的状况下只会调用一次,而节流的 状况会每隔必定时间(参数wait)调用函数。
节流是将屡次执行变成每隔一段时间执行。 每隔一段时间后执行一次,也就是下降频率,将高频操做优化成低频操做。
mousemove
事件的时候, 如鼠标移动。keyup
事件的状况, 如搜索。scroll
事件的时候, 譬如鼠标向下滚动中止时触发加载数据。resize
事件// function resizehandler(fn, delay){ // clearTimeout(fn.timer); // fn.timer = setTimeout(() => { // fn(); // }, delay); // } // window.onresize = () => resizehandler(fn, 1000);
function resizehandler(fn, delay){ let timer = null; return function() { const context = this; const args=arguments; clearTimeout(timer); timer = setTimeout(() => { fn.apply(context,args); }, delay); } } window.onresize = resizehandler(fn, 1000);
一段时间内触发事件只执行一次。javascript
function resizehandler(fn, delay, duration) { let timer = null; let beginTime = +new Date(); return function() { const context = this; const args = arguments; const currentTime = +new Date(); timer && clearTimeout(timer); if ((currentTime - beginTime) >= duration) { fn.call(context, args); beginTime = currentTime; } else { timer = setTimeout(() => { fn.call(context, args) }, delay); } } } window.onresize = resizehandler(fn, 1000, 1000);
Demo
CodePen-demojava
参考文章
http://www.alloyteam.com/2012...