jQuery页面滚动事件逻辑 - 如何调节 [英] jQuery page scroll event logic -- how to throttle

查看:108
本文介绍了jQuery页面滚动事件逻辑 - 如何调节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我的问题是,发送的功能更新太多。我想如果有办法扼杀.scroll(function(){})这样,更少的事件更新被触发。

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?

推荐答案

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

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

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

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

这篇关于jQuery页面滚动事件逻辑 - 如何调节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆