JS Coding Questions Logo
JS Coding Questions
#438💼 Interview💻 Code

What is throttling?

Advertisement

728x90

Throttling is a programming technique used to control the rate at which a function is executed. When an event is triggered continuously—such as during window resizing, scrolling, or mouse movement—throttling ensures that the associated event handler is not called more often than a specified interval. This helps improve performance by reducing the number of expensive function calls and preventing performance bottlenecks.

Common use cases:

* Window resize events

* Scroll events

* Mouse movement or drag events

* API rate limiting

How does throttling work?

Throttling will execute the function at most once every specified time interval, ignoring additional calls until the interval has passed.

Example: Throttle Implementation and Usage

JavaScript

css
1// Simple throttle function: allows 'func' to run at most once every 'limit' ms
2
3function throttle(func, limit) {
4  let inThrottle = false;
5  return function(...args) {
6  if (!inThrottle) {
7  func.apply(this, args);
8  inThrottle = true;
9  setTimeout(() => (inThrottle = false), limit);
10  }
11  };
12}
13
14// Usage: throttling a scroll event handler
15
16function handleScrollAnimation() {
17  console.log('Scroll event triggered');
18}
19
20window.addEventListener(
21  "scroll",
22  throttle(handleScrollAnimation, 100) // Will run at most once every 100ms
23);

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 9

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
438of476