函数节流-手写版本
test-throttle.js
/**
* @description 函数节流
* @param {Function} func 被节流函数
* @param {number} wait 时间
*/
function throttle(func, wait) {
let previous = 0;
return function () {
let now = Date.now(); // 1970/01/01 08:00:00 到现在的毫秒数
if (now - previous >= wait) {
func.apply(this, arguments);
previous = now;
}
};
}
// function throttle(func, wait) {
// let timeout;
// return function () {
// if (timeout) {
// return;
// }
// timeout = setTimeout(() => {
// timeout = null;
// func.apply(this, arguments);
// }, wait);
// };
// }
function log() {
console.log('2');
}
const throttled = throttle(log, 1000);
window.addEventListener('resize', throttled);
函数节流-lodash版本
_.throttle(func, [wait=0], [options={}])
func (Function): 要节流的函数。
[wait=0] (number): 需要节流的毫秒。
[options={}] (Object): 选项对象。
[options.leading=true] (boolean): 指定调用在节流开始前。
[options.trailing=true] (boolean): 指定调用在节流结束后。