有人可以解释Javascript中的“去抖动”功能

时间:2014-06-02 23:17:03

标签: javascript debouncing

我对" debouncing"感兴趣javascript中的函数,写在这里:http://davidwalsh.name/javascript-debounce-function

不幸的是,代码的解释不够清楚,我无法理解。任何人都可以帮我弄清楚它是如何工作的(我在下面留下了我的评论)。总之,我真的不明白这是如何工作的

   // 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.


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);
    };
};

编辑:复制的代码段之前在错误的位置callNow

9 个答案:

答案 0 :(得分:99)

问题中的代码与链接中的代码略有不同。在链接中,在创建新的提示之前检查(immediate && !timeout)。拥有它后立即模式永远不会开火。我已经更新了我的答案,以便从链接中注释工作版本。



function debounce(func, wait, immediate) {
  // 'private' variable for instance
  // The returned function will be able to reference this due to closure.
  // Each call to the returned function will share this common timer.
  var timeout;

  // Calling debounce returns a new anonymous function
  return function() {
    // reference the context and args for the setTimeout function
    var context = this,
      args = arguments;

    // Should the function be called now? If immediate is true
    //   and not already in a timeout then the answer is: Yes
    var callNow = immediate && !timeout;

    // This is the basic debounce behaviour where you can call this 
    //   function several times, but it will only execute once 
    //   [before or after imposing a delay]. 
    //   Each time the returned function is called, the timer starts over.
    clearTimeout(timeout);

    // Set the new timeout
    timeout = setTimeout(function() {

      // Inside the timeout function, clear the timeout variable
      // which will let the next execution run when in 'immediate' mode
      timeout = null;

      // Check if the function already ran with the immediate flag
      if (!immediate) {
        // Call the original function with apply
        // apply lets you define the 'this' object as well as the arguments 
        //    (both captured before setTimeout)
        func.apply(context, args);
      }
    }, wait);

    // Immediate mode and no wait timer? Execute the function..
    if (callNow) func.apply(context, args);
  }
}

/////////////////////////////////
// DEMO:

function onMouseMove(e){
  console.clear();
  console.log(e.x, e.y);
}

// Define the debounced function
var debouncedMouseMove = debounce(onMouseMove, 50);

// Call the debounced function on every mouse move
window.addEventListener('mousemove', debouncedMouseMove);




答案 1 :(得分:52)

这里需要注意的重要一点是,debounce会产生一个功能,它被关闭" timeout变量。 timeout变量在生成函数的每次调用期间都可以访问,即使debounce本身已经返回,可以更改不同的调用。

debounce的一般想法如下:

  1. 没有超时开始。
  2. 如果调用生成的函数,请清除并重置超时。
  3. 如果超时,请调用原始函数。
  4. 第一点只是var timeout;,它确实只是undefined。幸运的是,clearTimeout对其输入相当宽松:传递undefined计时器标识符会导致它无所事事,它不会抛出错误或其他东西。

    第二点由生成的函数完成。它首先在变量中存储有关调用的一些信息(this上下文和arguments),以便稍后可以将这些信息用于去抖动调用。然后它会清除超时(如果有一组),然后创建一个新的超时使用setTimeout替换它。 请注意,这会覆盖timeout的值,并且此值会在多个函数调用中持续存在!这允许去抖实际工作:如果多次调用该函数,timeout是用新计时器多次覆盖。如果不是这种情况,多次通话将导致启动多个计时器,其中所有保持活动状态 - 这些通话只会被延迟,但不会被去抖动。

    第三点是在超时回调中完成的。它取消设置timeout变量并使用存储的调用信息进行实际函数调用。

    immediate标志应该控制是否应该在之前调用或在定时器之后调用。如果是false,则在计时器被击中之后才会调用原始函数。如果它是true,则原始函数首先被调用,并且在计时器被命中之前不再被调用。

    但是,我确实认为if (immediate && !timeout)检查错误:timeout刚刚设置为setTimeout返回的计时器标识符,因此!timeout始终为{{1}在那一点上,因此永远不会调用该函数。 The current version of underscore.js似乎有一个稍微不同的检查,在调用false之前评估immediate && !timeout 。 (算法也有点不同,例如它没有使用setTimeout。)这就是为什么你应该总是尝试使用最新版本的库。 : - )

答案 2 :(得分:26)

去抖动函数在调用时不会执行,它们会在执行前等待一段可配置的持续时间暂停调用;每次新调用都会重新启动计时器。

限制函数执行,然后等待一段可配置的持续时间,然后才有资格再次触发。

去抖是非常适合按键事件;当用户开始输入然后暂停时,您将所有按键提交为单个事件,从而减少处理调用。

Throttle非常适合您只想让用户在一段时间内调用一次的实时端点。

查看Underscore.js的实施方案。

答案 3 :(得分:18)

我在一篇名为 Demistifying Debounce in JavaScript 的文章中写了一篇文章,其中我准确地解释了how a debounce function works并包含了一个演示。

我也没完全理解当我第一次遇到debounce功能时它是如何工作的。虽然尺寸相对较小,但它们实际上采用了一些非常先进的JavaScript概念!掌握范围,闭包和setTimeout方法将有所帮助。

话虽如此,下面是我在上面引用的帖子中解释和演示的基本去抖函数。

成品

// Create JD Object
// ----------------
var JD = {};

// Debounce Method
// ---------------
JD.debounce = function(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 || 200);
        if ( callNow ) { 
            func.apply(context, args);
        }
    };
};

解释

// Create JD Object
// ----------------
/*
    It's a good idea to attach helper methods like `debounce` to your own 
    custom object. That way, you don't pollute the global space by 
    attaching methods to the `window` object and potentially run in to
    conflicts.
*/
var JD = {};

// Debounce Method
// ---------------
/*
    Return 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 `wait` milliseconds. If `immediate` is passed, trigger the 
    function on the leading edge, instead of the trailing.
*/
JD.debounce = function(func, wait, immediate) {
    /*
        Declare a variable named `timeout` variable that we will later use 
        to store the *timeout ID returned by the `setTimeout` function.

        *When setTimeout is called, it retuns a numeric ID. This unique ID
        can be used in conjunction with JavaScript's `clearTimeout` method 
        to prevent the code passed in the first argument of the `setTimout`
        function from being called. Note, this prevention will only occur
        if `clearTimeout` is called before the specified number of 
        milliseconds passed in the second argument of setTimeout have been
        met.
    */
    var timeout;

    /*
        Return an anomymous function that has access to the `func`
        argument of our `debounce` method through the process of closure.
    */
    return function() {

        /*
            1) Assign `this` to a variable named `context` so that the 
               `func` argument passed to our `debounce` method can be 
               called in the proper context.

            2) Assign all *arugments passed in the `func` argument of our
               `debounce` method to a variable named `args`.

            *JavaScript natively makes all arguments passed to a function
            accessible inside of the function in an array-like variable 
            named `arguments`. Assinging `arguments` to `args` combines 
            all arguments passed in the `func` argument of our `debounce` 
            method in a single variable.
        */
        var context = this,   /* 1 */
            args = arguments; /* 2 */

        /*
            Assign an anonymous function to a variable named `later`.
            This function will be passed in the first argument of the
            `setTimeout` function below.
        */
        var later = function() {

            /*      
                When the `later` function is called, remove the numeric ID 
                that was assigned to it by the `setTimeout` function.

                Note, by the time the `later` function is called, the
                `setTimeout` function will have returned a numeric ID to 
                the `timeout` variable. That numeric ID is removed by 
                assiging `null` to `timeout`.
            */
            timeout = null;

            /*
                If the boolean value passed in the `immediate` argument 
                of our `debouce` method is falsy, then invoke the 
                function passed in the `func` argument of our `debouce`
                method using JavaScript's *`apply` method.

                *The `apply` method allows you to call a function in an
                explicit context. The first argument defines what `this`
                should be. The second argument is passed as an array 
                containing all the arguments that should be passed to 
                `func` when it is called. Previously, we assigned `this` 
                to the `context` variable, and we assigned all arguments 
                passed in `func` to the `args` variable.
            */
            if ( !immediate ) {
                func.apply(context, args);
            }
        };

        /*
            If the value passed in the `immediate` argument of our 
            `debounce` method is truthy and the value assigned to `timeout`
            is falsy, then assign `true` to the `callNow` variable.
            Otherwise, assign `false` to the `callNow` variable.
        */
        var callNow = immediate && !timeout;

        /*
            As long as the event that our `debounce` method is bound to is 
            still firing within the `wait` period, remove the numerical ID  
            (returned to the `timeout` vaiable by `setTimeout`) from 
            JavaScript's execution queue. This prevents the function passed 
            in the `setTimeout` function from being invoked.

            Remember, the `debounce` method is intended for use on events
            that rapidly fire, ie: a window resize or scroll. The *first* 
            time the event fires, the `timeout` variable has been declared, 
            but no value has been assigned to it - it is `undefined`. 
            Therefore, nothing is removed from JavaScript's execution queue 
            because nothing has been placed in the queue - there is nothing 
            to clear.

            Below, the `timeout` variable is assigned the numerical ID 
            returned by the `setTimeout` function. So long as *subsequent* 
            events are fired before the `wait` is met, `timeout` will be 
            cleared, resulting in the function passed in the `setTimeout` 
            function being removed from the execution queue. As soon as the 
            `wait` is met, the function passed in the `setTimeout` function 
            will execute.
        */
        clearTimeout(timeout);

        /*
            Assign a `setTimout` function to the `timeout` variable we 
            previously declared. Pass the function assigned to the `later` 
            variable to the `setTimeout` function, along with the numerical 
            value assigned to the `wait` argument in our `debounce` method. 
            If no value is passed to the `wait` argument in our `debounce` 
            method, pass a value of 200 milliseconds to the `setTimeout` 
            function.  
        */
        timeout = setTimeout(later, wait || 200);

        /*
            Typically, you want the function passed in the `func` argument
            of our `debounce` method to execute once *after* the `wait` 
            period has been met for the event that our `debounce` method is 
            bound to (the trailing side). However, if you want the function 
            to execute once *before* the event has finished (on the leading 
            side), you can pass `true` in the `immediate` argument of our 
            `debounce` method.

            If `true` is passed in the `immediate` argument of our 
            `debounce` method, the value assigned to the `callNow` variable 
            declared above will be `true` only after the *first* time the 
            event that our `debounce` method is bound to has fired.

            After the first time the event is fired, the `timeout` variable
            will contain a falsey value. Therfore, the result of the 
            expression that gets assigned to the `callNow` variable is 
            `true` and the function passed in the `func` argument of our
            `debounce` method is exected in the line of code below.

            Every subsequent time the event that our `debounce` method is 
            bound to fires within the `wait` period, the `timeout` variable 
            holds the numerical ID returned from the `setTimout` function 
            assigned to it when the previous event was fired, and the 
            `debounce` method was executed.

            This means that for all subsequent events within the `wait`
            period, the `timeout` variable holds a truthy value, and the
            result of the expression that gets assigned to the `callNow`
            variable is `false`. Therefore, the function passed in the 
            `func` argument of our `debounce` method will not be executed.  

            Lastly, when the `wait` period is met and the `later` function
            that is passed in the `setTimeout` function executes, the 
            result is that it just assigns `null` to the `timeout` 
            variable. The `func` argument passed in our `debounce` method 
            will not be executed because the `if` condition inside the 
            `later` function fails. 
        */
        if ( callNow ) { 
            func.apply(context, args);
        }
    };
};

答案 4 :(得分:2)

我们现在都在使用 Promises

我见过的许多实现都使问题过于复杂或存在其他卫生问题。现在是 2021 年,我们已经使用 Promises 很长时间了——这也是有充分理由的。 Promise 清理异步程序并减少发生错误的机会。在这篇文章中,我们将编写自己的 debounce。此实现将 -

  • 在任何给定时间(每个去抖动任务)至多有一个待处理的 promise
  • 通过正确取消挂起的承诺来阻止内存泄漏
  • 仅解析最新的 promise
  • 通过实时代码演示展示正确的行为

我们用它的两个参数编写 debouncetask 去抖动,以及延迟的毫秒数,ms。我们为其本地状态引入了一个本地绑定,t -

function debounce (task, ms) {
  let t = { promise: null, cancel: _ => void 0 }
  return async (...args) => {
    try {
      t.cancel()
      t = deferred()
      await t.promise
      await task(...args)
    }
    catch (_) { /* prevent memory leak */ }
  }
}

我们依赖于一个可重用的 deferred 函数,该函数创建了一个在 ms 毫秒内解析的新承诺。它引入了两个本地绑定,promise 本身,cancel 它的能力 -

function deferred (ms) {
  let cancel, promise = new Promise((resolve, reject) => {
    cancel = reject
    setTimeout(resolve, ms)
  })
  return { promise, cancel }
}

点击计数器示例

在第一个示例中,我们有一个按钮来计算用户的点击次数。事件侦听器使用 debounce 附加,因此计数器仅在指定的持续时间后递增 -

// debounce, deferred
function debounce (task, ms) { let t = { promise: null, cancel: _ => void 0 }; return async (...args) => { try { t.cancel(); t = deferred(ms); await t.promise; await task(...args); } catch (_) { console.log("cleaning up cancelled promise") } } }
function deferred (ms) { let cancel, promise = new Promise((resolve, reject) => { cancel = reject; setTimeout(resolve, ms) }); return { promise, cancel } }

// dom references
const myform = document.forms.myform
const mycounter = myform.mycounter

// event handler
function clickCounter (event) {
  mycounter.value = Number(mycounter.value) + 1
}

// debounced listener
myform.myclicker.addEventListener("click", debounce(clickCounter, 1000))
<form id="myform">
<input name="myclicker" type="button" value="click" />
<output name="mycounter">0</output>
</form>

实时查询示例,“自动完成”

在第二个示例中,我们有一个带有文本输入的表单。我们的 search 查询使用 debounce -

附加

// debounce, deferred
function debounce (task, ms) { let t = { promise: null, cancel: _ => void 0 }; return async (...args) => { try { t.cancel(); t = deferred(ms); await t.promise; await task(...args); } catch (_) { console.log("cleaning up cancelled promise") } } }
function deferred (ms) { let cancel, promise = new Promise((resolve, reject) => { cancel = reject; setTimeout(resolve, ms) }); return { promise, cancel } }

// dom references
const myform = document.forms.myform
const myresult = myform.myresult

// event handler
function search (event) {
  myresult.value = `Searching for: ${event.target.value}`
}

// debounced listener
myform.myquery.addEventListener("keypress", debounce(search, 1000))
<form id="myform">
<input name="myquery" placeholder="Enter a query..." />
<output name="myresult"></output>
</form>

答案 5 :(得分:1)

你想要做的是:如果你试图一个接一个地调用一个函数,第一个应该取消并且新的应该等待给定的超时然后执行。那么实际上你需要一些方法来取消第一个函数的超时?但是怎么样? 您可以调用该函数,并传递返回的timeout-id,然后将该ID传递给任何新函数。但上面的解决方案更优雅。

它的作用是有效地使timeout变量在返回函数的范围内可用。所以,当一个&#39;调整大小&#39;如果事件被触发,则不会再次调用debounce(),因此timeout内容不会更改(!),并且仍可用于&#34;下一个函数调用&#34;。

这里的关键基本上是我们每次调整resize事件时调用内部函数。也许更清楚的是我们是否想象所有resize-events都在一个数组中:

var events = ['resize', 'resize', 'resize'];
var timeout = null;
for (var i = 0; i < events.length; i++){
    if (immediate && !timeout) func.apply(this, arguments);
    clearTimeout(timeout); // does not do anything if timeout is null.
    timeout = setTimeout(function(){
        timeout = null;
        if (!immediate) func.apply(this, arguments);
    }
}

您看到timeout可用于下一次迭代吗? 在我看来,没有理由将this重命名为contentarguments重命名为args

答案 6 :(得分:1)

javascript中的简单反跳方法

<!-- Basic HTML -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Debounce Method</title>
</head>
<body>
  <button type="button" id="debounce">Debounce Method</button><br />
  <span id="message"></span>
</body>
</html>

  // JS File
  var debouncebtn = document.getElementById('debounce');
    function debounce(func, delay){
      var debounceTimer;
      return function () {
        var context = this, args = arguments;
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(function() {
          func.apply(context, args)
        }, delay);
      }
    }

// Driver Code
debouncebtn.addEventListener('click', debounce(function() {
    document.getElementById('message').innerHTML += '<br/> Button only triggeres is every 3 secounds how much every you fire an event';
  console.log('Button only triggeres in every 3 secounds how much every you fire an event');
},3000))

运行时示例JSFiddle:https://jsfiddle.net/arbaazshaikh919/d7543wqe/10/

答案 7 :(得分:0)

这是一个变体,它总是在第一次调用去抖动功能时触发它,并带有更具描述性的变量:

function debounce(fn, wait = 1000) {
  let debounced = false;
  let resetDebouncedTimeout = null;
  return function(...args) {
    if (!debounced) {
      debounced = true;
      fn(...args);
      resetDebouncedTimeout = setTimeout(() => {
        debounced = false;
      }, wait);
    } else {
      clearTimeout(resetDebouncedTimeout);
      resetDebouncedTimeout = setTimeout(() => {
        debounced = false;
        fn(...args);
      }, wait);
    }
  }
};

答案 8 :(得分:0)

简单的防抖动功​​能:-

HTML:-

<button id='myid'>Click me</button>

JavaScript:-

    function debounce(fn, delay) {
      let timeoutID;
      return function(...args){
          if(timeoutID) clearTimeout(timeoutID);
          timeoutID = setTimeout(()=>{
            fn(...args)
          }, delay);
      }
   }

document.getElementById('myid').addEventListener('click', debounce(() => {
  console.log('clicked');
},2000));