Hey guys, today I’m going to explain how you can improve the speed of your javascript code without having to do much effort, we just need the famous lodash library and its powerful debounce method.

First, of, I will explain shortly what debounce is, so let’s get going.

Debounce:

So, what is debounce? It basically limits the number of times a function can be called within a certain time. A quick example: you have set an event listener for the mouse move event and that listener fires a method which does some calculations, now try to imagine how many times that method it’s going to get called as the mouse moves, could be thousand times easily, and even though the method itself might not be slow, the user might be interested only in the final result after he stops moving the mouse, so, why don’t we limit the number of times this method can be fired as the user moves the mouse? Let’s see how it’s done:

Example:

Demo – Code here

You’ll need to open the inspector to see the magic. Done? Now, without the debounce, see how many times the WriteDOM method fires as we move the mouse, a lot of times right?

And with the debounce activated, VOILÀ, the user needs to do a little pause so that the method gets fired.

This technique, in situations where the method could be heavy or where the user is only interested in the final result, is a very simple way of optimizing your javascript code.

References:

Special Thanks to @ednjv for a nice translation of this 😉

If you have a problem implemented or a simpler way to do this work please leave a comment below, Regards.