Skip to content

Instantly share code, notes, and snippets.

@chule
Created September 10, 2023 19:20
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 chule/7af3902bb3dde6c3f2957f40813a4926 to your computer and use it in GitHub Desktop.
Save chule/7af3902bb3dde6c3f2957f40813a4926 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<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="debounce" type="text" placeholder="debounce" />
<button type="button" id="throttle">throttle</button>
<script>
const debounce = (func, wait) => {
let timeout;
return (...args) => {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
};
document.getElementById("debounce").addEventListener(
"keydown",
debounce((e) => {
console.log(e.target.value);
}, 1000)
);
const throttle = (func, wait) => {
let lastTime = 0;
return (...args) => {
const now = Date.now();
if (now - lastTime >= wait) {
func(...args);
lastTime = now;
}
};
};
document.getElementById("throttle").addEventListener(
"click",
throttle(() => {
console.log("clicked");
}, 2000)
);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment