jQuery页面滚动事件逻辑 – 如何限制

我有一些jQuery监听器设置如下:

$(document).scroll(function() { if( $(this).scrollTop()  change1 && $(this).scrollTop()  change2) { updateBarChart('valuem', 'remove') //updateSteamChart('','steam') } }); 

直截了当。 滚动更改时会更新某些图表。

我的问题是,这是发送太多function更新。 我想如果有一种方法来限制.scroll(function(){})那么,会触发更少的事件更新。

想法?

实现限制的一种相当简单的方法可能是对随机值添加一个检查,以便它只触发一定比例的时间:

 $(document).scroll(function() { //Only fires 10% of the time if (Math.random() < 0.1) { if( $(this).scrollTop() < change1) { updateBarChart('valuem', 'opencomparison'); } else if ( $(this).scrollTop() > change1 && $(this).scrollTop() < change2) { updateBarChart('valuef', 'opencomparison'); } else if ($(this).scrollTop() > change2) { updateBarChart('valuem', 'remove'); } } }); 

或者,您可以使用计时器,使其每x毫秒仅触发一次:

 $(document).scroll(function() { //Only fires at most once every half-second if (timer > 500) { timer = 0; if( $(this).scrollTop() < change1) { updateBarChart('valuem', 'opencomparison'); } else if ( $(this).scrollTop() > change1 && $(this).scrollTop() < change2) { updateBarChart('valuef', 'opencomparison'); } else if ($(this).scrollTop() > change2) { updateBarChart('valuem', 'remove'); } } }); var timer = 0; setInterval(function () { timer += 50; }, 50);