DEV Community

Cover image for Project 78 of 100 - Implementing a Debounce Function

Project 78 of 100 - Implementing a Debounce Function

James Hubert
Customer experience-centric product lover and front-end developer in New York. Follow my dev Twitter:
・2 min read

Hey! I'm on a mission to make 100 React.js projects. Please follow my profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!

Link to today's deployed app: Link
Link to the repo: github

Ok so you got me. I didn't build a totally new React project from scratch today, nor is the emphasis of this project React.

It is however an important Javascript function within a React application and it does improve the user experience of the Notes app from project 77.

So in the first version of this notes application we only saved notes when the window closes. This works, but in a browser I think this would leave users feeling uncomfortable not knowing whether or not their work was saved.

That's why, in so many online notes applications, the document automatically saves every time a change is made and you are told or shown the timestamp of the most recent save.

But if the document actually made a request to the server and saved every time the user pressed a key that would be incredibly, unnecessarily costly.

One way around this is to wait for the user to stop typing, and then save. We can do this with what is called a debounce function.

Classically, this is a function which takes two arguments- a callback function to be passed to it and an integer that stands for the delay, or how long to wait until you perform the callback passed to it.

Here is mine, which I put in a separate file for helper functions:

export default function debounce(callback,wait) {
  let id = window.setTimeout(function() {}, 0);

  while (id--) {
      window.clearTimeout(id); // will do nothing if no timeout with id is present

  let timeout = null
  return (...args) => {
    const next = () => callback(...args)
    timeout = setTimeout(next, wait)
Enter fullscreen mode Exit fullscreen mode

This brilliant little solution allows me to efficiently save the user's text at convenient times and display the most recent save's timestamp just like in Evernote or Google Docs!

If you like projects like this and want to stay up to date with more, check out my Twitter @jwhubert91, I follow back! See you tomorrow for another project.

Discussion (0)