Underscore debounce vs vanilla Javascript setTimeout

问题描述 投票:0回答:5

我知道 Undercore.js 中的

debounce
返回一个函数,该函数将推迟执行直到等待时间结束。

我的问题是,与普通 Javascript 中的常规

debounce
函数相比,使用
setTimeout
是否有优势?它们的作用不一样吗?

javascript underscore.js settimeout lodash delayed-execution
5个回答
19
投票

它们非常不同,并且用于完全不同的情况。

  1. _.debounce
    返回
    function
    setTimeout
    返回
    id
    ,您可以使用它来取消超时。

  2. 无论您调用_.debounce返回的函数多少次,它在给定的时间范围内只会运行一次。

var log_once = _.debounce(log, 5000);

function log() {
  console.log('prints');
}

log_once();
log_once();
log_once();
log_once();
log_once();

var id = setTimeout(function() {
  console.log('hello');
}, 3000);
clearTimeout(id);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>


12
投票

setTimeout
debounce
绝不是同一件事。
setTimeout
只需等待
n
毫秒并调用提供的函数。另一方面,
debounce
返回一个函数,该函数仅在上次调用函数后
n
毫秒后调用回调。

差异巨大。去抖/节流(它们不是同一件事)函数通常用于减少由于用户输入而导致的函数调用量。想象一下自动完成/提前输入字段。您可能会在每次击键时执行一次 ajax 请求,但这可能会有点繁重,因此您可以对函数进行反跳,这样它只会在最后一次击键后

之后 200 毫秒触发。 您可以在此处阅读文档:

https://lodash.com/docs#debounce


9
投票
function debouncing with underscore

的文章,其中包括 underscore 在其实现中使用的源代码: // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; };

debounce 函数充当您想要调用的实际函数的生成器,这样状态就可以保留在闭包内部,如下所示:

// example function let sayHello = (name) => console.log(`Hi ${name}`) // generate a debounced version with a min time between calls of 2 seconds let sayHelloDebounced = debounce(sayHello, 2000) // call however you want sayHelloDebounced('David')

堆栈片段中的演示

function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; let sayHello = (name) => console.log(`Hi ${name}`) let sayHelloDebounced = debounce(sayHello, 2000) sayHelloDebounced('David') sayHelloDebounced('David') sayHelloDebounced('David')

其他实现


0
投票

在正式英语中,debounce 的作用与 setTimeout 和clearTiemout 的作用相同。 如果您不想使用 debounce,您可以将 setTimeout 与clearTiemout 一起使用来实现相同的行为。

let timer; function setTimer(){ clearTimeout(timer); timer = setTimeout(() => console.log("here"), 1000); }; setTimer(); setTimer(); setTimer(); setTimer(); // here [![enter image description here][1]][1]



-1
投票
Javascript 中的去抖和节流

© www.soinside.com 2019 - 2024. All rights reserved.