Sometimes events occur too frequently (e.g., scroll, resize, mousemove). We use throttling and debouncing techniques to limit the frequency of function execution.
1// Debouncing - executes the function only after a specified time without new calls
2function debounce(func, delay) {
3 let timeoutId;
4 return function(...args) {
5 clearTimeout(timeoutId);
6 timeoutId = setTimeout(() => func.apply(this, args), delay);
7 };
8}
9
10// Throttling - limits the frequency of function execution
11function throttle(func, limit) {
12 let inThrottle;
13 return function(...args) {
14 if (!inThrottle) {
15 func.apply(this, args);
16 inThrottle = true;
17 setTimeout(() => inThrottle = false, limit);
18 }
19 };
20}
21
22// Using debouncing for search
23const searchInput = document.getElementById('dino-search');
24const debouncedSearch = debounce((query) => {
25 console.log(`Searching for dinosaurs: ${query}`);
26 searchDinosaurs(query);
27}, 300);
28
29searchInput.addEventListener('input', (e) => {
30 debouncedSearch(e.target.value);
31});
32
33// Using throttling for scroll
34const throttledScroll = throttle(() => {
35 const scrollPosition = window.scrollY;
36 updateNavigationHighlight(scrollPosition);
37 updateProgressBar(scrollPosition);
38}, 100);
39
40window.addEventListener('scroll', throttledScroll);