【问题标题】:Javascript: How do I tweak my debounce function to take an IF conditional?Javascript:如何调整我的 debounce 函数以采用 IF 条件?
【发布时间】:2012-06-29 23:46:54
【问题描述】:

我发现了一个错误,并对其进行了跟踪。
你可以see a simplified example of my code here

事实证明,我需要对 if() 语句进行去抖动处理,而不是对函数本身进行去抖动处理。
我想将 debounce 保留为独立函数,但我不确定如何传递条件。

任何指针?

代码如下:

var foo = function(xyz) {
    alert(xyz);
};

function setter(func, arg1, arg2) {
    return {
        fn: func,
        arg1: arg1,
        arg2: arg2
    };
}

function debounce(someObject) {
    var duration = someObject.arg2 || 100;
    var timer;
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(function() {
        someObject.fn(someObject.arg1);
        timer = 0;
    }, duration);
}

var toggle = true;

if (toggle) {
    debounce(setter(foo, 'The best things in life are worth waiting for.', 1250));
} else {
    foo('Instant gratification is sweet!!');
}

【问题讨论】:

  • 那么这到底是做什么的呢?我知道谴责电子产品,但似乎无法弄清楚这如何适用于此。
  • 你可以移动if (toggle) {检查insidefoo函数...当然,如果你有多个函数,这会违反DRY。
  • @arttronics 据我了解,OP 想要消除(例如延迟)if-check。他不想立即测试toggle,而是稍后,在函数实际被调用的那一刻。
  • @Šime Vidas :是的,我正试图让我的代码尽可能 DRY(不要重复自己),这就是为什么我希望将 debounce 保持为独立的一些排序。
  • @sachleen 现实生活中的实现是在设置 UI 的输入字段上。输入有上限和下限(根据环境动态生成)。如果我们需要强制执行限制,那自然必须等到用户(或应该)完成输入他们的值。 HTH。

标签: javascript


【解决方案1】:

使用您的示例,为什么不将切换作为 arg 1 传递...类似于:

var toggle = true;
var debouncedFunk = function(toggle) {
  if (toggle)
    // the function call
  else
    // something else
};
debounce(debouncedFunk, toggle, 1250);

您还应该考虑使用函数对象.call.apply 方法。它们用于调用函数并传入参数。以示例函数为例:

var example = function(one, two) { 
  // Logic here
};

你可以通过三种方式调用它:

// First
example(1, 2);
// Second
example.call({}, 1, 2);
// Third
example.apply({}, [ 1, 2 ]);

第一种是调用函数的标准方式。第一个和.call 的区别在于.call 的第一个参数是函数的上下文对象(this 将指向函数内部),其他参数在此之后传递(以及一个已知的.call 需要列表。.apply 的好处是您可以将数组传递给参数函数,它们将被适当地分配给参数列表,第一个参数仍然是上下文对象。

它将简化您的去抖动功能,而不是像您目前那样处理结构化对象。

对您的去抖的建议:

var debounce = function(funk, delay) {
  var args = [];
  if (arguments.length > 2)
    args = [].slice.call(arguments, 2);
  setTimeout(function() { funk.apply({}, args); }, delay);
};

将当前的 if 更改为:

var toggle = true;
var debouncedFunk = function(toggle) {
  if (toggle)
    // Do if true
  else
    // DO if false
};
debounce(debouncedFunk, 1000, toggle);

可能信息太多(抱歉)?

最后一点,我建议使用已经实现这些功能(以及许多其他有用功能)的框架(如果可能),例如Underscore。使用下划线,您的示例将如下所示:

// Define debouncedFunk and toggle
debouncedFunk = _.bind(debouncedFunk, {}, toggle);
debouncedFunk = _.debounce(debouncedFunk, 1000);
debouncedFunk();

编辑

修复了下划线示例,_.debounce 返回的函数只有在延迟后才会执行,但仍需要调用。

【讨论】:

  • +1 您唯一遗漏的是目录。很好的答案!
  • 哇@izuriel,这是一个一堆的重要信息。在我真正理解这一切之前可能需要一点消化:),但这太棒了。谢谢。
  • @mOrloff 没问题,希望对您有所帮助!并感谢 arttronics!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-08
  • 2019-09-13
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 2015-07-22
相关资源
最近更新 更多