Underscore debounce vs vanilla Javascript setTimeout

nik*_*ohn 5 javascript settimeout delayed-execution underscore.js lodash

我知道debounce在Undercore.js中会返回一个函数,该函数将推迟执行直到等待时间结束.

我的问题是,使用vanilla Javascript中debounce的常规setTimeout函数是否有优势?他们俩都不一样吗?

Kyl*_*Mit 10

您还可以在普通 JavaScript 中实现您自己的去抖动。一篇被广泛引用的文章是 David Walsh 的关于使用下划线进行函数去抖的文章,其中包括下划线在其实现中使用的源代码:

// 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);
    };
};
Run Code Online (Sandbox Code Playgroud)

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')
Run Code Online (Sandbox Code Playgroud)

堆栈片段中的演示

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')
Run Code Online (Sandbox Code Playgroud)

其他实现


Phi*_*lip 7

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

巨大的差异。去抖动/节流(它们不是一回事)函数通常用于减少由于用户输入而导致的函数调用量。想象一个自动完成/预先输入字段。您可能会在每次击键时执行 ajax 请求,但这可能会变得很重,因此您可以对函数进行去抖,因此它只会在最后一次击键200 毫秒触发。

您可以在此处阅读文档:https : //lodash.com/docs#debounce

  • ...除非您的事件处理程序首先取消超时然后重置它。然后,你实际上有相同的行为。 (3认同)

Avi*_*ash 7

它们非常不同,用于完全不同的情况.

  1. _.debounce返回a function,setTimeout返回一个id可以用来取消timeOut的东西.

  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);
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,[**This Vanilla `debounce`**](https://github.com/JDMcKinstry/debounce) 方法返回超时,因此如果您也选择手动取消它。 (2认同)