javascriptdebouncing

Debounce in Javascript


I am currently learning debounce in Javascript and I came across two ways of writing debounce functions that works the same. One is a lot simpler like regular function, the other one is the complicated one that everyone seems to use.

Version 1:

<input type="text" oninput="betterFunction()">

<script>
function getData() {
  console.log('Data Fetched')
}

function debounce(callback, delay) {
  let timer
  return function() {
    clearTimeout(timer)
    timer = setTimeout(() => {
      callback();
    }, delay)
  }
}

const betterFunction = debounce(getData, 1000)
</script>


Version 2:

<input type="text" oninput="debounce()">

<script>
let timer

function debounce() {
  clearTimeout(timer)
  timer = setTimeout(() => {
    console.log('Data Fetched');
  }, 1000)
}
</script>

What is the difference between these two ways of debouncing if they both gives the same result? PS: I am surprised that I have never seen anyone use the 'version 2', ofcourse something must me wrong. Could anybody explain the differences please?


Solution

  • Debounce function is a javascript programming pattern for delaying execution of a function, your Version 1 is the commonly accepted pattern for implementing a debounce feature because its better than Version 2 for the reasons listed by MR. Polywhirl.

    The pattern is actually making use of a javascript feature called a closure, which allows inner function (the function being returned by debounce) to access their outer scope (specifically in this case, the declared variable timer).

    You can read about closures in detail here to gain further understanding why version 1 is the preferred version, but this explanation/example of closures might be easier to grasp at first.