【问题标题】:"setTimeout" VS "debounce" plugin - to defer code execution on events"setTimeout" VS "debounce" 插件 - 延迟事件的代码执行
【发布时间】:2014-09-25 12:22:30
【问题描述】:

我想推迟一些事件代码的执行。 使用标准 setTimeout 函数和插件去抖动 (link to debounce) 之间到底有什么区别?

这里有一个例子 setTimeout:

var timeout;
$(window).on("scroll", function() {

    clearTimeout(timeout);
    timeout = setTimeout(function() {

        doSomethingFunction();

    }, 500);

});

这里有一个去抖动的例子

$(window).on("scroll",

    $.debounce(500, doSomethingFunction)

);

当然,使用 debounce 代码会更短,但还有其他好处吗? 哪个会更快?

【问题讨论】:

    标签: javascript jquery jquery-plugins debouncing


    【解决方案1】:

    debounce 在内部使用setTimeout,因此差异与setTimeout 被触发的次数有关。

    debounce 限制它触发setTimeout 的次数。如果在短时间内发送多个请求,则只有一个会通过。

    var timeout_id = setTimeout(
        debounce_mode ? clear
        : exec, debounce_mode === undefined ? delay - elapsed
        : delay
    );
    

    您可以查看the source code 了解更多信息。

    插件将通过设置超时 id 来处理超时。

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多