Last active
February 18, 2022 08:42
-
-
Save yingray/4406a4e95001aac9a908ef117803a30a to your computer and use it in GitHub Desktop.
Implement debounce and throttle
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
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); |
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
<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> |
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
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