Code
function debounce(func, wait, immediate = false) { let timeout; return function executedFunction(...args) { const later = () => { timeout = null; if (!immediate) func(...args); }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func(...args); };}module.exports = debounce;const debounce = require('./debounce');// Debounce search inputconst searchInput = document.getElementById('search');const debouncedSearch = debounce((query) => { console.log('Searching for:', query); // API call here}, 300);searchInput.addEventListener('input', (e) => { debouncedSearch(e.target.value);});// Immediate execution variantconst debouncedResize = debounce(() => { console.log('Window resized');}, 300, true);window.addEventListener('resize', debouncedResize);
Comments
No comments yet. Be the first!
Please login to leave a comment.