javascript - 下划线 _.debounce() : How to execute method only the last time received?

标签 javascript underscore.js

_.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/

相关文章:

javascript - lodash:通过另一个 JSON 对象过滤对象数组

javascript - d3 js 双向水平条形图

javascript - 在混合应用程序开发中使用本地存储作为 "Local Database"- 危险还是有用?

javascript - 在 Javascript 对象数组中查找属性名称

javascript - 对同一页面上的多个链接使用 Javascript 灯箱效果

java - 在 Java 7 或更低版本中,HOWTO 使用在 map 中找到的键/值来过滤 map 对象列表

javascript - 下面的 setTimeout 中的匿名函数中的 "this"的值是多少?

json - 在 Node.js 中将字符串转换为带有嵌套键的 JSON 对象的最佳方法是什么?

javascript - 如何更改 NodeJS CLI 提示符

javascript - 如何使用 underscoreJS 连接两个数组的值