滚动事件触发次数过多。我只希望它每秒最多发射一次 [英] Scroll event firing too many times. I only want it to fire a maximum of, say, once per second

查看:441
本文介绍了滚动事件触发次数过多。我只希望它每秒最多发射一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无限滚动的页面。它会计算页面末尾与当前页面之间的差异,如果此差异足够小,则会加载更多内容。使用jQuery代码是这样的:

I have a page with "infinite scroll". It calculates the difference between the end of the page and the current page and loads more content if this difference is small enough. The code is soemthing like this using jQuery:

$(window).on('scroll', function() {
    if (window.pageYOffset > loadMoreButton.offsetTop - 1000)
        # load more content via ajax
}

现在,问题在于每次滚动时,每个滚动都会触发多次此事件。我希望每隔x毫秒触发一次。我该怎么做?

Now, the problem is that every time I scroll, this event fires multiple times per scroll. I would like fire at most every x milliseconds. How would I do this?

推荐答案

查看Underscore.js库的油门方法。

Check out the Underscore.js library's "throttle" method.

http://underscorejs.org/#throttle

示例给出正是你所询问的 - 限制你处理滚动事件的频率。

The example it gives is exactly what you're asking about - limiting how often you have to handle scroll events.

这篇关于滚动事件触发次数过多。我只希望它每秒最多发射一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆