Skip to content

Instantly share code, notes, and snippets.

@debabrata100
Last active December 1, 2019 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debabrata100/390be010007da890ba90a7e1ad908d65 to your computer and use it in GitHub Desktop.
Save debabrata100/390be010007da890ba90a7e1ad908d65 to your computer and use it in GitHub Desktop.
How to implement debounce in javascript using html button as an example for click action
<html>
<body>
<button id="debounce">
Debounce
</button>
<script>
var button = document.getElementById("debounce");
const debounce = (func, delay) => {
let tid;
return (...args) => {
if(tid){
clearTimeout(tid);
}
tid = setTimeout(()=>{
func(...args);
},delay)
}
}
button.addEventListener('click', debounce(function() {
alert("Hello\nNo matter how many times you" +
"click the debounce button, I get " +
"executed once every 300 ms !!!")
}, 300));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment