jQuery page scroll event logic — how to throttle

前端 未结 1 1416
傲寒
傲寒 2020-12-22 05:33

I have some jQuery listeners setup as follows:

$(document).scroll(function() {

    if( $(this).scrollTop() < change1) { 
            updateBarChart(\'val         


        
相关标签:
1条回答
  • 2020-12-22 05:55

    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);
    
    0 讨论(0)
提交回复
热议问题