Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain the 'this' in debounce function in JavaScript?

With this debounce function:

function debounce(fn, delay) {
    var timer
    return function () {
      var context = this
      var args = arguments
      clearTimeout(timer)
      timer = setTimeout(function () {
        fn.apply(context, args)
      }, delay)
    }
  }

can someone explain why I should use fn.apply(context,args) instead of fn() only?

I know .apply will change the context and var context = this will make the context always be the same as the context in fn(). I can't find a scenario where using fn() and fn.apply(context, args) gives a different result.

Can someone give me an example?

like image 504
Moon Avatar asked Oct 16 '20 18:10

Moon


People also ask

How do you explain Debounce?

Bouncing is the tendency of any two metal contacts in an electronic device to generate multiple signals as the contacts close or open; debouncing is any kind of hardware device or software that ensures that only a single signal will be acted upon for a single opening or closing of a contact.

What is debounce function in JavaScript?

The debounce() function forces a function to wait a certain amount of time before running again. The function is built to limit the number of times a function is called. The Send Request() function is debounced. Requests are sent only after fixed time intervals regardless of how many times the user presses the button.

Why do we need debounce?

The debounce function delays the processing of the keyup event until the user has stopped typing for a predetermined amount of time. This prevents your UI code from needing to process every event and also drastically reduces the number of API calls sent to your server.

What is debounce function in JavaScript?

Debounce Function in JavaScript. Debounce function limits the rate at which a function can fire. For example, a user authentication form where user can provide their credentials and click on the button to log in. Users can click multiple times on the same button which would in turn calls the function multiple times.

How to create a delay between debounce and setTimeout in JavaScript?

In the first run, when the debounce function is called, we call the setTimeout () function to create a delay and once the timeout is complete, we execute the function. If the debounce function is called between the delay, we simply reset the timer and create a new delay using setTimeout () function. Let’s use our debounce function.

Can you call a debounce function multiple times?

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

How does debounce work with timeouts?

The important thing to note here is that debounce produces a function that is "closed over" the timeout variable. The timeout variable stays accessible during every call of the produced function even after debounce itself has returned, and can change over different calls. Start with no timeout.


1 Answers

Consider the following class:

class Foo {
  constructor () {
    this.a = 'a';
    this.bar = debounce(this.bar, 500);
  }

  bar () {
    console.log(this.a);
  }
}

const foo = new Foo();
foo.bar();
foo.bar();
foo.bar();

So what gets logged, and when, and how many times? You are going to see one value logged, one time, about half a second after the last call. With the definition you posted you'll see a. If you omit the contextual part you'll see undefined:

function debounceWithoutCtx(fn, delay) {
    var timer
    return function (...args) {
      clearTimeout(timer)
      timer = setTimeout(function () {
        fn(...args)
      }, delay)
    }
 }
  
like image 179
Jared Smith Avatar answered Oct 20 '22 10:10

Jared Smith