Here's code for both rate limiting and debouncing, tailored for use in JavaScript and ReactJS:
✅ 1. Rate Limiting in JavaScript
Rate limiting ensures a function runs at most once every X milliseconds, no matter how often it's
called.
🔹 JavaScript Throttle Function (Rate Limiter)
js
CopyEdit
function throttle(func, delay) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
func.apply(this, args);
};
🔹 Example Usage
js
CopyEdit
window.addEventListener('resize', throttle(() => {
console.log('Resize event throttled');
}, 1000)); // Runs at most once every 1 second
✅ 2. Debouncing in ReactJS
Debouncing delays the execution of a function until after a certain period of inactivity.
🔹 Custom Hook: useDebounce
jsx
CopyEdit
import { useState, useEffect } from 'react';
function useDebounce(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const handler = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debounced;
🔹 Example Usage in a React Component
jsx
CopyEdit
import React, { useState } from 'react';
function SearchComponent() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 500);
useEffect(() => {
if (debouncedQuery) {
console.log('Searching for:', debouncedQuery);
// Make API call here
}, [debouncedQuery]);
return (
<input
type="text"
placeholder="Search..."
onChange={(e) => setQuery(e.target.value)}
/>
);
🔁 Rate Limit vs Debounce Summary
Technique Use Case Behavior
Throttle Limit executions (e.g., resize) Fires at intervals
Debounce Delay until idle (e.g., search) Fires after pause