Debouncing input

So I have the following code below. I’m trying to create a debouncer for my inputs on react. Right now all I’m trying to do is see if I can delay them from being logged on the console. It doesn’t work at all and I was wondering if anyone had some insight. I really don’t understand the process, I saw a youtube video that I followed which gave me the code for debounce.

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

  onChangeHandler(event) {
    debounce((event) => {
      console.log(event.target.value);
    }, 500);
  }

Hi,

Just looking at it :

  1. Have you used function debounce(fn, delay) or have you set it equal to var or a const ?
    2)Debounce is a function that returns another function. A bit like this.
function count() { 
     let count = 0
     return function() {
         return count +=1
    }    
}

const counting = count()
counting() // -1
counting( ) // -2


What you do is, you call count and set it equal to a variable. That variable simply returns a function it doesn’t do anything.
Then you call that variable. Here it is called counting() and that function will keep subtracting one from count. The value is saved AFTER it has been called.
In your handler I don’t see debounce being set equal to a variable and that variable being called. I don’t know about the event handler but you can do this :

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

var bouncing = debounce( function() {
  let a = 2
  let b = 3
  console.log( a + b );
}, 2000) 

now call bouncing

bouncing()

–> wait two seconds and 5 appears
Does that help ? By the way, I got this kind of code from a free and excellent udacity course called Object Oriented Javascript and a function returning a function is called a closure. It is an advanced concept and not explained in the FCC curriculum. Do the course, I did it several times because it is so excellent and it does cover stuff that is complicated.

Greets,
Karin