How do you use throttling with an example?

Throttling is a technique used to limit the number of times a function can be called over time. It helps in controlling the flow of code execution and is particularly useful in scenarios such as scrolling, resizing, or API requests.
throttling, JavaScript, function control, performance optimization
function throttle(fn, wait) { let lastTime = 0; return function(...args) { const now = Date.now(); if (now - lastTime >= wait) { lastTime = now; fn.apply(this, args); } }; } // Example usage const log = () => console.log('Function executed'); const throttledLog = throttle(log, 2000); // Execute log at most every 2 seconds // Simulating function calls setInterval(throttledLog, 500); // Calls `throttledLog` every 500ms

throttling JavaScript function control performance optimization