Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Last active October 24, 2022 13:27
Show Gist options
  • Save treyhuffine/d628c0cd2e7d25f829159e08c29e92c0 to your computer and use it in GitHub Desktop.
Save treyhuffine/d628c0cd2e7d25f829159e08c29e92c0 to your computer and use it in GitHub Desktop.
// Originally inspired by David Walsh (https://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
// `wait` milliseconds.
const debounce = (func, wait) => {
let timeout;
// This is the function that is returned and will be executed many times
// We spread (...args) to capture any number of parameters we want to pass
return function executedFunction(...args) {
// The callback function to be executed after
// the debounce time has elapsed
const later = () => {
// null timeout to indicate the debounce ended
timeout = null;
// Execute the callback
func(...args);
};
// This will reset the waiting every function execution.
// This is the step that prevents the function from
// being executed because it will never reach the
// inside of the previous setTimeout
clearTimeout(timeout);
// Restart the debounce waiting period.
// setTimeout returns a truthy value (it differs in web vs Node)
timeout = setTimeout(later, wait);
};
};
@xgqfrms
Copy link

xgqfrms commented Oct 19, 2022

question

I think it's no need manually clear timeoutid inside the later function

const debounce = (func, wait) => {
  let timeoutId;
  return (...args) => {
    const later = () => {
      func(...args);
      // no need to manually clear timeoutId
      // timeoutId = null;
      // clearTimeout(timeoutId);
    };
    //  the right place to clear timeoutId
    timeoutId && clearTimeout(timeout);
    // timeoutId = setTimeout(later, wait);
    timeoutId = setTimeout(() => {
       func(...args);
    }, wait);
  };
};

optimization version

const debounce = (func, wait) => {
  let timeoutId;
  let that = this;
  // context
  return (...args) => {
    timeoutId && clearTimeout(timeout);
    timeoutId = setTimeout(() => {
       // apply, args array
       func.apply(that, args);
       // call, args list
       // func.call(that, ...args);
    }, wait);
  };
};

ref

https://levelup.gitconnected.com/debounce-in-javascript-improve-your-applications-performance-5b01855e086

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment