[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 leadingmaxWait, 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");

 

posted @   Zhentiw  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-04-11 [RxJS] Extend Promises by Adding Custom Behavior
2019-04-11 [Algorithm] Binary tree: Level Order Traversal
2019-04-11 [SSH] Intro to SSH command
2018-04-11 [Tailwind] Extending Tailwind with Responsive Custom Utility Classes
2018-04-11 [Tailwind] Control What Variations are Generated for Each Utility Class Module in Tailwind
2016-04-11 [RxJS] Creation operator: of()
点击右上角即可分享
微信分享提示