【发布时间】:2018-02-25 15:24:15
【问题描述】:
谁能告诉我制作纯 JS anology 的方法是什么:
window.addEventListener('scroll', _.throttle(callback, 500, { leading: true, trailing: false}));
【问题讨论】:
-
查看 lodashs 源代码。
标签: javascript lodash
谁能告诉我制作纯 JS anology 的方法是什么:
window.addEventListener('scroll', _.throttle(callback, 500, { leading: true, trailing: false}));
【问题讨论】:
标签: javascript lodash
希望对你有帮助
function throttle(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
window.addEventListener('scroll', throttle(callback, 500, { leading: true, trailing: false}));
【讨论】:
.target { height: 1000px } as css 来添加滚动到页面,你可以看到@ 987654322@,我刚刚添加了css
这里是来源:https://github.com/lodash/lodash/blob/master/throttle.js
function throttle(func, wait, options) {
let leading = true
let trailing = true
if (typeof func != 'function') {
throw new TypeError('Expected a function')
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading
trailing = 'trailing' in options ? !!options.trailing : trailing
}
return debounce(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
})
}
参考这里的 debounce - https://github.com/lodash/lodash/blob/master/debounce.js
【讨论】:
https://github.com/niksy/throttle-debounce/blob/master/throttle.js