loading...

Using Throttle in Javascript

bmsvieira profile image Bruno Vieira ・2 min read

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);

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);

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.

Posted on May 30 by:

bmsvieira profile

Bruno Vieira

@bmsvieira

Web Developer for more than 7 years, PHP, JavaScript, SQL, Node.js

Discussion

markdown guide