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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay