GitHub

advancedThrottle()

Advanced throttling function with customizable delay, leading/trailing calls, max call limit, and cancellation support.

Core Function
Performance
Control
Syntax
advancedThrottle(func, delay, options)
Parameters

func
Function

The function to throttle.

delay
number

Delay in milliseconds between allowed calls.

options
object
optional

Configuration options.

  • leading - Whether to invoke at the start of the delay (default: true)
  • trailing - Whether to invoke at the end of the delay (default: true)
  • maxCalls - Maximum allowed calls before throttling disables (default: Infinity)
Returns

Function
- Throttled function with control methods:

  • cancel() - Cancel pending invocations
  • flush() - Immediately invoke pending function
Examples

Basic Throttling

// Basic throttle with 1 second delay
const logMessage = () => console.log("Function called!");
const throttledLog = advancedThrottle(logMessage, 1000);

// Call multiple times rapidly
throttledLog(); // Executes immediately
throttledLog(); // Ignored (within delay)
throttledLog(); // Ignored (within delay)

// After 1 second, next call will execute

Leading and Trailing Options

// Leading only (execute immediately, ignore trailing)
const leadingOnly = advancedThrottle(
  () => console.log("Leading call"),
  1000,
  { leading: true, trailing: false }
);

// Trailing only (wait for delay, then execute)
const trailingOnly = advancedThrottle(
  () => console.log("Trailing call"),
  1000,
  { leading: false, trailing: true }
);

// Both leading and trailing (default)
const bothCalls = advancedThrottle(
  () => console.log("Both calls"),
  1000,
  { leading: true, trailing: true }
);

Max Calls Limit

// Limit to maximum 5 calls
const limitedThrottle = advancedThrottle(
  (count) => console.log(`Call #${count}`),
  500,
  { maxCalls: 5 }
);

// After 5 calls, function stops executing
for (let i = 1; i <= 10; i++) {
  setTimeout(() => limitedThrottle(i), i * 100);
}
// Only first 5 calls will execute

Cancel and Flush

const expensiveOperation = () => {
  console.log("Performing expensive operation...");
};

const throttled = advancedThrottle(expensiveOperation, 2000);

// Schedule a call
throttled();

// Cancel the pending call
setTimeout(() => {
  throttled.cancel();
  console.log("Operation cancelled");
}, 1000);

// Or flush immediately
const anotherThrottled = advancedThrottle(expensiveOperation, 2000);
anotherThrottled();

setTimeout(() => {
  anotherThrottled.flush(); // Execute immediately
}, 500);

Scroll Event Throttling

// Throttle scroll events for performance
const handleScroll = () => {
  const scrollTop = window.pageYOffset;
  console.log(`Scroll position: ${scrollTop}`);
  
  // Update UI based on scroll position
  if (scrollTop > 100) {
    document.body.classList.add('scrolled');
  } else {
    document.body.classList.remove('scrolled');
  }
};

const throttledScroll = advancedThrottle(handleScroll, 100, {
  leading: true,
  trailing: true
});

// Add to scroll event
window.addEventListener('scroll', throttledScroll);

// Cleanup function
function cleanup() {
  window.removeEventListener('scroll', throttledScroll);
  throttledScroll.cancel();
}

API Request Throttling

// Throttle API requests to avoid rate limiting
const searchAPI = async (query) => {
  console.log(`Searching for: ${query}`);
  try {
    const response = await fetch(`/api/search?q=${query}`);
    const results = await response.json();
    displayResults(results);
  } catch (error) {
    console.error('Search failed:', error);
  }
};

const throttledSearch = advancedThrottle(searchAPI, 300, {
  leading: false,  // Don't search immediately
  trailing: true,  // Search after user stops typing
  maxCalls: 50     // Limit to 50 searches per session
});

// Use with input field
const searchInput = document.getElementById('search');
searchInput.addEventListener('input', (e) => {
  throttledSearch(e.target.value);
});

Button Click Protection

// Prevent rapid button clicks
const submitForm = async (formData) => {
  console.log("Submitting form...");
  try {
    await fetch('/api/submit', {
      method: 'POST',
      body: formData
    });
    console.log("Form submitted successfully");
  } catch (error) {
    console.error("Submission failed:", error);
  }
};

const throttledSubmit = advancedThrottle(submitForm, 2000, {
  leading: true,   // Execute first click immediately
  trailing: false, // Ignore subsequent clicks
  maxCalls: 3      // Allow max 3 submissions
});

// Attach to button
document.getElementById('submit-btn').addEventListener('click', (e) => {
  e.preventDefault();
  const formData = new FormData(document.getElementById('myForm'));
  throttledSubmit(formData);
});