Blog>
Snippets

Throttling actions with middleware

Implement a middleware that throttles the dispatch of certain actions to limit the rate at which they can be called.
// HTML
<button id="throttleBtn">Click me</button>
A simple HTML button that will trigger throttled actions when clicked.
/* CSS */
#throttleBtn {
  padding: 10px 20px;
  font-size: 16px;
  margin: 20px;
  cursor: pointer;
}
Basic CSS for styling the button.
// JavaScript Middleware for Throttling

// Simple throttle function that prevents a function from being called more than once within a specified delay
function throttle(func, delay) {
  let lastTime = 0;
  return function(...args) {
    const now = new Date().getTime();
    if (now - lastTime >= delay) {
      func.apply(this, args);
      lastTime = now;
    }
  };
}

// Example action to be throttled
function myAction() {
  console.log('Action triggered', new Date().toLocaleTimeString());
}

// Throttled function with a 2-second delay
const throttledAction = throttle(myAction, 2000);

document.getElementById('throttleBtn').addEventListener('click', throttledAction);
This script creates a middleware function 'throttle' to limit the rate at which myAction can be executed. It's applied to a button click event. The throttled function will only execute once every 2 seconds, regardless of how many times the button is clicked.