_.debounce()
使用 _.debounce(function,x
最多每 x 毫秒触发一次) .. 我想修改它以仅执行一个方法 x
last 之后的毫秒 _.debounce()
.
我该怎么做? (顺便说一句,我读过 $.debounce
就是这么做的。)
我试过这样做,但它不是防弹的(更不用说屁股丑了)
var timeout;
$(window).on("resize",_.debounce(function(){
if(timeout){
clearTimeout(timeout);
}
//when debounce comes in we cancel it.. this means only the latest debounce actually fires.
//not bullet proof
timeout = setTimeout(resizeMap,100);
},50));
如何优雅地做到这一点?
最佳答案
阅读您的评论后,现在更清楚了。
well perhaps it's my browser (infrequent resize events, causing _debounce to be called? testing on Chrome), but while resizing, I keep getting multiple calls to the body of the debounced function. As if it's behaving exactly as _.throttle now I come to think of it.. Weird stuff.
50 毫秒是一个非常短的去抖时间。我打赌它按预期工作,你只需要更长的去抖时间。 50ms 是 1/20 秒。我不确定窗口调整大小事件会这么快触发。但即使是这样,在调整大小时鼠标移动的最微小的停顿也可能会触发这种情况。
在你的 debounced 函数中删除所有这些 setTimeout
废话,并将 debounce 时间设置为更像 250
的东西,我打赌它会像你想要的那样工作。
关于javascript - 下划线 _.debounce() : How to execute method only the last time received?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13729656/