[Javascript] Build lodash.debounce from Scratch
This lesson will demonstrate how to recreate a simplified version of the popular lodash.debounce method from scratch. I literally failed a job interview by messing up this question, so watch carefully!
Debounce is an incredible tool most commonly used to prevent responding too quickly to user input that is in motion. For example, preventing excessive AJAX requests made while a user types into an autocomplete field or quickly responding to window resize events without bringing your browser to a halt.
Our approach is to build the simplest debounce
method possible using a setTimeout which gets cleared each time the supplied function is called thereby delaying the execution of our function until input stops for a given amount of time.
The Lodash implementation of debounce includes support for a number of options including leading
, maxWait
, and trailing
which we have not covered in this video, but may in future lessons.
Variations
Modern implementations of setTimeout
include support for additional arguments which get passed into your function so an alternative to the approach used in this lesson would be setTimeout(fn, wait, ...args)
ES5 Compatbility
If you are in an es5 environment skip the rest/spread syntax and use:
var args = Array.prototype.slice.call(arguments)
And later, in your setTimeout function:
fn.apply(null, args)
There are some really great resources out there to learn more about debounce, here are my two favorites:
- https://css-tricks.com/debouncing-throttling-explained-examples/
- http://benalman.com/projects/jquery-throttle-debounce-plugin/
function debounce(fn, wait) { let timer; return (...args) => { if (timer) { clearTimeout(timer); } timer = setTimeout(() => fn.apply(null, args), wait); }; } module.exports = { debounce };
index.js
function log(name) { console.log("Log the function", name); } const debouncedLog = debounce(log, 4000); debouncedLog("zhen");