Categories
JavaScript Answers

How to add simple throttling in JavaScript?

Spread the love

Sometimes, we want to add simple throttling in JavaScript.

In this article, we’ll look at how to add simple throttling in JavaScript.

How to add simple throttling in JavaScript?

To add simple throttling in JavaScript, we can create our own function.

For instance, we write

const throttle = (func, timeFrame) => {
  let lastTime = 0;
  return () => {
    const now = Date.now();
    if (now - lastTime >= timeFrame) {
      func();
      lastTime = now;
    }
  };
};

to define the throttle function that takes the func function and the timeFrame in milliseconds that func is allowed to run once.

In it, we return a function that checks now - lastTime is bigger than or equal to timeFrame.

If it is, then we call func since it hasn’t been called within the timeFrame.

And then we set lastTime to now.

now is the current datetime’s timestamp in milliseconds.

Conclusion

To add simple throttling in JavaScript, we can create our own function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *