gpt4 book ai didi

javascript - jQuery页面滚动事件逻辑——如何节流

转载 作者:行者123 更新时间:2023-12-02 16:59:41 26 4
gpt4 key购买 nike

我有一些 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() {}) ,这样可以减少触发的事件更新。

想法?

最佳答案

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

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

关于javascript - jQuery页面滚动事件逻辑——如何节流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25860108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com