How can I prevent a function from being called too quickly or too many times in a row?

Posted by Prem Tiwari | Updated on

If you have an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be done by using:

  • throttling: sample changes based on a time based frequency (eg _.throttle)
  • debouncing: publish changes after a period of inactivity (eg _.debounce)
  • requestAnimationFrame throttling: sample changes based on requestAnimationFrame (eg raf-schd)

See this visualization for a comparison of throttle and debounce functions.

If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@] Your question and answer will appear on and help other developers.

Related Questions & Answers