節流: 保證一段時間內只執行一段代碼(例如滾動,oninput,onkeypress,onscroll,resize等事件觸發頻率非常高)
一個函數執行一次後,只有大於設定的執行週期,纔會執行第二次
throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options = options || {};
var later = function() {
previous = options.leading === false ? 0 : new Date();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date();
if (!previous && options.leading === false) {
previous = now;
}
var remaining = wait - (now - previous);
//存下上下文作用域
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
防抖:在一定時間段的連續函數調用,只讓其執行一次
var debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
return function() {
context = this;
args = arguments;
timestamp = new Date();
var later = function() {
var last = (new Date()) - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
}
};
var callNow = immediate && !timeout;
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) {
result = func.apply(context, args);
}
return result;
};
}