【问题标题】:jQuery page scroll event logic -- how to throttlejQuery页面滚动事件逻辑——如何节流
【发布时间】:2014-09-16 03:14:49
【问题描述】:

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

$(document).scroll(function() {

    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')
        //updateSteamChart('','steam')
}
});

足够直截了当。滚动更改时会更新一些图表。

我的问题是,这发送了太多的功能更新。我想有办法限制 .scroll(function() {}) 那样,触发的事件更新更少。

想法?

【问题讨论】:

    标签: javascript jquery d3.js parallax


    【解决方案1】:

    实现节流的一种相当简单的方法可能是添加对随机值的检查,使其仅在一定百分比的时间内触发:

    $(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);
    

    【讨论】:

      猜你喜欢
      • 2021-08-21
      • 2011-11-07
      • 2012-06-05
      • 2011-12-27
      • 2018-04-29
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多