Czasami wydarzenia występują zbyt często (np. scroll, resize, mousemove). Używamy technik throttling i debouncing, żeby ograniczyć częstotliwość wykonywania funkcji.
1// Debouncing - wykonuje funkcję dopiero po określonym czasie bez nowych wywołań
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 - ogranicza częstotliwość wykonywania funkcji
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// Użycie debouncing dla wyszukiwania
23const searchInput = document.getElementById('dino-search');
24const debouncedSearch = debounce((query) => {
25 console.log(`Wyszukiwanie dinozaurów: ${query}`);
26 searchDinosaurs(query);
27}, 300);
28
29searchInput.addEventListener('input', (e) => {
30 debouncedSearch(e.target.value);
31});
32
33// Użycie throttling dla scroll
34const throttledScroll = throttle(() => {
35 const scrollPosition = window.scrollY;
36 updateNavigationHighlight(scrollPosition);
37 updateProgressBar(scrollPosition);
38}, 100);
39
40window.addEventListener('scroll', throttledScroll);