holyZhengs
2 min readNov 17, 2019

Two skills you must understand if you are a Javascript Developer

In our program, we often use event listeners to do something we need. But as a qualified development, we must ensure that our programs have high performance. The two tricks I am going to talk about today are related to event listeners in our code.

In some special cases, you need to make some special restrictions to ensure that your event listener does not burden your program’s performance.

For example,

  1. The click events of button element
  2. oninput of the input element
  3. window scroll event listener
  4. and so on

When these events happen, if you don’t do special treatment, it is likely that your listening events will be executed many times in a short time. This undoubtedly wastes resources and at the same time degrades the performance of your program. So how can we avoid this happening? Two skills can help you!

These two skills are throttle and debounce.

What is throttle? 🍀

Throttling is the limitation of your event listener callback function that can only be executed once in a period of time. Here is the demo.

Even if the event listener is triggered multiple times in succession, the callback function can only be executed once a second.

What is debounce? 🚦

If the event listener is triggered multiple times in a short time, debounce will disable the execution of the callback function unless the time interval between the two triggers reaches a standard. Here is a demo.

If you trigger the event multiple times in a short time, the callback function will only execute once.

These two techniques can effectively enhance the performance of your program in specific scenarios. Which one to use depends on the actual scenario.

In the End, hope that this article is helpful to you, thank you for reading. 🎉 🎉 🎉