JavaScript消抖(debounce)与节流(throttle)
有时候会因为window的resize、scroll事件、touchmove/mousemove拖动事件等等而频繁执行DOM操作、资源加载等行为,导致浏览器卡顿甚至崩溃。其实大多的时候只要事件结束后才执行下一步的,针对这两种情况就出现了debounce和throttle两种解决办法。
(function(){
var dt = {
// 防抖debounce
debounce: function(fn, delay) {
let args = arguments,
_this = this,
timer = null;
return function () {
if (timer) {
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(_this, args);
}, delay);
} else {
timer = setTimeout(function () {
fn.apply(_this, args);
}, delay);
}
}
},
// 节流throttle
throttle: function(fn, delay) {
let args = arguments,
_this = this,
timer = null,
remaining = 0,
previous = new Date();
return function () {
let now = new Date();
remaining = now - previous;
if (remaining >= delay) {
if (timer) {
clearTimeout(timer);
}
fn.apply(_this, args);
previous = now;
} else {
if (!timer) {
timer = setTimeout(function () {
fn.apply(_this, args);
previous = new Date();
}, delay - remaining);
}
}
};
}
}
window.dt = dt
})()
使用
<script type="text/javascript">
function hehe(e,ar) {
console.log(e,'==',ar)
}
// window.onscroll = dt.debounce(hehe,1000)
window.onscroll = dt.throttle(hehe,1000)
</script>