Created
October 23, 2024 15:18
-
-
Save CalebCurry/340a9cdb1aeafb6f1d0067cdec2436e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Throttle and Debounce Example</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script> | |
</head> | |
<body> | |
<button id="clickMe">Click Me (throttled)!</button> | |
<br><br> | |
<input type="text" id="inputField" placeholder="Type something..." /> | |
<script> | |
// Function to run on button click (throttled) | |
function onButtonClick() { | |
console.log('Button clicked!'); | |
} | |
// Throttled version of the function, with a 1000ms limit | |
const throttledButtonClick = _.throttle(onButtonClick, 1000); | |
// Add event listener for button click | |
document.getElementById('clickMe').addEventListener('click', throttledButtonClick); | |
// Function to run when input changes (debounced) | |
function onInputChange(event) { | |
console.log('Input changed to:', event.target.value); | |
} | |
// Debounced version of the function, with a 500ms delay | |
const debouncedInputChange = _.debounce(onInputChange, 500); | |
// Add event listener for input change | |
document.getElementById('inputField').addEventListener('input', debouncedInputChange); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment