JavaScript snippets can save time, enhance readability, and help solve common coding tasks. Below are five versatile snippets that are easy to implement and can come in handy in a wide range of projects.
1. Debounce Function
If you’ve ever dealt with events like window resizing, scrolling, or button clicks, you know they can fire repeatedly and quickly. Debouncing allows you to delay a function’s execution until after the last event trigger, which improves performance.
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
// Usage
window.addEventListener('resize', debounce(() => {
console.log("Resized!");
}, 300));
In this example, resizing the window logs “Resized!” only once after 300ms, no matter how frequently the event fires within that period.
2. Throttling
Throttling limits how often a function can execute within a set time frame. This is useful for performance-heavy tasks, like continuous button presses or scroll events.