_.debounce() 使用 _.debounce(function,x 最多触发每 x 毫秒).. 我想调整它以仅在 最后一个 x 之后执行一个方法 _.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));

如何优雅地做到这一点?

最佳答案

阅读您的评论后,现在更清楚了。



50ms 是一个相当低的去抖动时间。我打赌它按预期工作,您只需要更长的去抖动时间。 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/

10-11 12:06