Skip to content

Instantly share code, notes, and snippets.

@amerllica
Last active June 3, 2019 10:28
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 amerllica/e71d742c10a68a60b3091c06810a3eff to your computer and use it in GitHub Desktop.
Save amerllica/e71d742c10a68a60b3091c06810a3eff to your computer and use it in GitHub Desktop.
JavaScript Debounce Function
const searchInput = document.getElementById('search-input');
const searchText = document.getElementById('search-text');
const debounce = (func, wait = 100) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
};
};
const result = e => searchText.innerText = e.target.value;
searchInput.addEventListener('input', debounce(result, 500));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vanilla Starter</title>
</head>
<body>
<input type="text" id="search-input" />
<div id="search-text">GoodBye</div>
<script type="text/javascript" src="./debounce.js" defer></script></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment