简体   繁体   English

如何调节和去抖功能?

[英]How to throttle AND debounce a function?

I wondered if there's a way to throttle and debounce a function called by $( window ).resize (or any other). 我想知道是否有一种方法可以限制和消除$( window ).resize (或其他任何函数)调用的函数。 I've tried to only throttle but the problem is since I'm using 100% of the width of the body, if i stop resizing before the next execution of the function, the horizontal scroll apear. 我试图仅节流,但是问题是因为我正在使用100%的宽度,如果我在下一次执行该功能之前停止调整大小,则会出现水平滚动。 Therefore I need to debounce it to make shure it also execurte after the resizing is done. 因此,我需要对它进行去抖动处理,以确保调整大小后它也可以执行。

If you can think of another way, please let me know! 如果您能想到其他方法,请告诉我!

I've typically done this with setTimeout : 我通常使用setTimeout完成此操作:

// Timer handle; 0 = invalid handle
var scrollTimer = 0;
$("window").on("scroll", function() {
    // Clear any pending work (it's okay to call with 0 [invalid handle], but add a guard if you like)
    clearTimeout(scrollTimer);
    // Schedule callback in X milliseconds
    setTimeout(scrollHandler, 10); // 10 = 10ms, adjust as you like
});
function scrollHandler() {
    scrollTimer = 0;
    // ...
}

If a new scroll even comes in within the interval, the previous call to scrollHandler never happens and we schedule a new one. 如果在该时间间隔内甚至出现了新的滚动,则对上一次对scrollHandler调用将永远不会发生,我们将安排新的滚动。 X milliseconds after the last one, scrollHandler gets called. 最后一个X毫秒后, scrollHandler

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM