DEV Community

Bruno Vieira
Bruno Vieira

Posted on

3 1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs