节流:多少秒只触发一次
// 缺点:第一次事件能触发,但是最后一次事件不能触发
function throttle1(func, delay) {
var prev = 0;
return function() {
if (Date.now() - prev >= delay) {
prev = Date.now();
func.apply(this, arguments);
}
};
}
防抖:多少秒后触发,flag 是立即执行
function debounce(func, delay, flag) {
var timer = null;
return function() {
var that = this;
clearTimeout(timer);
if (flag && !timer) {
func.apply(this, arguments);
}
timer = setTimeout(function() {
func.apply(that, arguments);
}, delay);
};
}
防抖节流结合版:第一次能触发,最后一次也能触发
function combine(func, delay) {
var timer = null;
var pre = 0;
return function() {
var that = this;
if (Date.now() - pre >= delay) {
clearTimeout(timer);
timer = null;
pre = Date.now();
func.apply(that, arguments);
} else if (!timer) {
timer = setTimeout(function() {
func.apply(that, arguments);
}, delay);
}
};
}
图片懒加载
https://github.com/dirkhe1051931999/common-demo/tree/master/canvaslazyloading
确认评论邮箱
邀请制评论