使用下划线_.debounce()触发单个事件

Using Underscore _.debounce() to trigger a single event

本文关键字:单个 事件 下划线 debounce      更新时间:2023-09-26

我有以下函数,它是从输入文本字段上的keyPress侦听器调用的。_.debounce()工作正常,除了在时间段之后只触发函数1次,它会在keyPress事件发生时触发多次。

console.log("Pre Debounce");
var debounced = _.debounce(function() {
    console.log("Field updated!");
}, 2000);
debounced();

是否有办法限制_.debounce函数仅在时间段后触发1次?

可能每次都在事件内部构造debounce函数。如果是这种情况,那么将debounce函数置于事件响应代码之外。据我所知,debdedfunction应该只生成一次,然后多次调用。

另一件事,可能会变得奇怪的是,当你做一个异步调用(例如,与ajax自动完成),它需要比你的等待时间debounce然后请求可能会触发以后出现debounce是不工作。

有可能您的debounce函数执行的时间比用户键入的时间长。在这种情况下,您希望通过传递第三个参数(immediate)作为true来确保防止双重脱扣。

debounce函数签名为:_.debounce(function, wait, [immediate])

因此将代码改为:

console.log("Pre Debounce");
var debounced = _.debounce(function() {
    console.log("Field updated!");
}, 2000, true);
debounced();