在前端开发中,有时会为页面绑定resize事件,或者为一个页面元素绑定拖拽事件(mousemove),这种事件有一个特色,在一个正常的操做中,有可能在一个短的时间内触发很是屡次事件绑定程序。
DOM操做时很消耗性能的,若是你为这些事件绑定一些操做DOM节点的操做的话,那就会引起大量的计算,在用户看来,页面可能就一时间没有响应,这个页面一会儿变卡了变慢了。在IE下,若是你绑定的resize事件进行较多DOM操做可能直接就崩溃了。html
这个你轻轻一拖,就会执行几十次,这对性能不友好的。前端
输入完成后统一发送请求,最后一我的说了算,只认最后一次浏览器
若是用户每次输入都发送请求,冗余过多,用户中止输入字符350毫秒后,在发送请求app
window.onscroll=function() { console.log("滚动") }
function debounce(fn, delay) { var timer = null; return function () { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); }; }
使用,会发现次数明显的下降了函数
window.onscroll = debounce(function () { console.log("啊哈哈") }, 100)
应用场景性能
某一段时间只执行一次,好比说350ms固定发送请求this
function throttle(fn, threshhold, scope) { threshhold || (threshhold = 250); var last, deferTimer; return function () { var context = scope || this; var now = +new Date, args = arguments; if (last && now < last + threshhold) { // hold on to it clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fn.apply(context, args); }, threshhold); } else { last = now; fn.apply(context, args); } }; } $('body').on('mousemove', throttle(function (event) { console.log('tick'); }, 1000));
应用场景.net
网上有这段话code
什么玩意儿???这么麻烦的吗?防抖还好,大部分都能达到理想的效果,但是节流就没那么理想了。节流是技能冷却啊!就是要点一下立马触发,进入冷却,等冷却,结束继续能点。然而大多版本都是:点击等一下子才触发,进入冷却。前面多了莫名的等待时间,不是立马触发的.......htm