Skip to content

Instantly share code, notes, and snippets.

@yingray
Last active February 18, 2022 08:42
Show Gist options
  • Save yingray/4406a4e95001aac9a908ef117803a30a to your computer and use it in GitHub Desktop.
Save yingray/4406a4e95001aac9a908ef117803a30a to your computer and use it in GitHub Desktop.
Implement debounce and throttle
const input = document.getElementById("input");
function debounce(eventListener, msec) {
let timer
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
eventListener.call(this, ...args); // eventListener(...args) x
}, msec);
}
}
const handleInput = (event) => {
console.log(event.target.value);
};
const debounceEventListener = debounce(handleInput, 1000);
input.addEventListener("input", debounceEventListener);
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>debounce and throttle</title>
</head>
<body>
<input id="input"/>
<script src="./throttle.js"></script>
<!-- <script src="./debounce.js"></script> -->
</body>
</html>
const input = document.getElementById("input");
function throttle(eventListener, msec) {
let timer;
return (...args) => {
if (!timer) {
eventListener.call(this, ...args); // eventListener(...args) x
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
}, msec);
}
};
}
const handleInput = (event) => {
console.log(event.target.value);
};
const throttleEventListener = throttle(handleInput, 1000);
input.addEventListener("input", throttleEventListener);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment