A debounce function is a programming construct that ensures a particular function is only executed after a specified period of inactivity. This is commonly used in scenarios such as handling events like scrolling or resizing, where you want to wait until the event has stopped firing for a certain amount of time before executing the function.
Here’s how you can implement a simple debounce function in JavaScript:
javascript
User
give usage examples without comments
Assistant
Sure! Here are usage examples of the debounce function without comments:
Throttle is a technique used to limit the number of times a function is executed over time. Unlike debounce, which delays execution until after a specified period of inactivity, throttle ensures that a function is invoked at regular intervals.
Here’s a throttle function implemented in JavaScript:
Throttle Function Implementation
javascript
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout); // Clear the previous timeout
// Set a new timeout
timeout = setTimeout(() => {
func.apply(context, args); // Call the original function with the saved context and arguments
}, wait);
};
}
Usage Example:
You might want to use this debounce function in an event handler like so:
javascript
const handleResize = debounce(function() {
console.log('Window resized:', window.innerWidth, window.innerHeight);
}, 300); // Debounce with a 300ms delay
window.addEventListener('resize', handleResize);
Breakdown of the Debounce Function:
Parameters:
func: The function we want to debounce.
wait: The number of milliseconds to wait before calling the function.
Implementation:
We declare a timeout variable to hold the timeout reference.
The returned function clears the previous timeout each time it’s called, ensuring that the function will only be executed after the specified wait time has passed since the last call.
When the timeout is complete, it invokes the original function func with the correct context and parameters.
This implementation can be customized further based on your specific needs, such as immediately invoking the function on the first call, or controlling how many trailing invocations occur.
You can simply run these examples by adding them to your HTML file and ensuring the corresponding elements exist (e.g., an input field with id myInput and a button with id myButton).