Search code examples
javascriptjqueryd3.jsparallax

jQuery page scroll event logic -- how to throttle


I have some jQuery listeners setup as follows:

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

Straightforward enough. Some charts are updated when scrolling changes.

My issue is, this is sending too many function updates. I'd like if there were a way to throttle the .scroll(function() {}) That way, fewer event updates are fired.

Ideas?


Solution

  • A fairly simple way of achieving throttling might be to add a check against a random value so that it only fires a certain percentage of the time:

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

    Alternatively, you could use a timer so that it only fires once per x miliseconds:

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