Javascript debounce function not working

<script>
      let newValue = '';

      const getData = () => {
          console.log('fetching data', newValue);
      }
      

      const debounce = function (fn, d) {
        let timer;
        return function () {
          clearTimeout(timer);
          timer = setTimeout(() => {
            fn();
          }, d);
        };
      };


      const betterFunction = ({ target: { value } }) => {
        newValue = value;
        debounce(getData, 300);
      };

    </script>
  </head>
  <body>
    <input type="text" onkeyup="betterFunction(event)" />
  </body>

debounce returns a function
But
you are doing nothing with the
returned function

do this …
debounce(getData, 300)();
and the returned function will run

Also, running debounce on each keyup will cause creation of new timer each time, which is not what you want. You need to create debounced function first and then run it:

const getDataDebounced = debounce(getData, 300);
const betterFunction = ({ target: { value } }) => {
    newValue = value;
    getDataDebounced();
};