【发布时间】:2016-09-03 21:12:51
【问题描述】:
我尝试防止多次滚动事件,例如250 毫秒内只有一个事件。为此,我在 Internet 中找到了下面的 debounce 功能。但我无法正确使用它。怎么了?
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// my code..
$(window).on('scroll', function (e) {
debounce(function() {
// The stuff below doesn't work.
var scrollTop = $(window).scrollTop();
if (scrollTop > 50) {
$('.title').addClass('fixedPosition');
} else {
$('.title').removeClass('fixedPosition');
}
}, 250);
});
【问题讨论】:
-
我会向窗口对象添加一个互斥锁,并使用 setTimeout 函数每 250 毫秒异步释放它
-
删除包装函数,只需调用
debouce作为on的处理程序参数。 -
与here 讨论的类似。您需要调用返回的函数 =>
debounce(function(){/**/}(), 250); -
@Teemu 我听不懂。你能写出来吗?
标签: javascript jquery