DEV Community

Bruno Vieira
Bruno Vieira

Posted on

Using Throttle in Javascript

Hey guys,

This time, im going to talk Throttle.
What is Throttle and what it is used for?

A throttle is a technique used in the browser to improve performance by limiting the number of events your code needs to handle.

Throttle is used when you want to execute a callback at a controlled rate, allowing you to handle intermediate states repeatedly at each fixed interval of time.

For example, using ScrollEventListener

document.addEventListener("scroll", function() { 
    console.log("Hey!");
}, false);
Enter fullscreen mode Exit fullscreen mode

It will be executed dozens of times (maybe more) per second when you scroll, it is a waste of memory, code overflow, and you probably don't even need to run that code so many times to achieve your goal.

So, you can use Throttle with the following code:

// Main throttle function
function throttle (func, interval) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function () {
      timeout = false;
    };
    if (!timeout) {
      func.apply(context, args)
      timeout = true;
      setTimeout(later, interval)
    }
  }
}

// My function that will run repeatedly at each fixed interval of time.
var myHeavyFunction = throttle(function() {

          // Your code here

}, 200); // Adjust interval of time

// Add EventListener
window.addEventListener('scroll', myHeavyFunction);
Enter fullscreen mode Exit fullscreen mode

That's it! now you can control the interval of time wich your funciont will run.

You can use Throttle with the following Events:

  • Scroll
  • Mouse Move
  • Window Resize
  • Etc...

It also exists Debounce that allows you to “group” multiple raised sequential functions into a single function, but that's for another post.

I hope it helps someone.

Take a look at my most recent project: VanillaJS Fully Customizable SelectBoxes

thank you.

Top comments (0)