jQuery page scroll event logic — how to throttle

断了今生、忘了曾经 提交于 2019-11-28 12:02:30

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/25860108/jquery-page-scroll-event-logic-how-to-throttle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!