Skip to content

Instantly share code, notes, and snippets.

@peduarte
Last active August 25, 2022 14:55
Show Gist options
  • Save peduarte/7ee475dd0fae1940f857582ecbb9dc5f to your computer and use it in GitHub Desktop.
Save peduarte/7ee475dd0fae1940f857582ecbb9dc5f to your computer and use it in GitHub Desktop.
Vanilla Debounce
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Vanilla Debounce</title>
<!-- put additional styles and scripts here -->
</head>
<body>
<!-- put markup and other contents here -->
</body>
</html>
// Vanilla Debounce implementation
function debounce(func, wait = 100) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
};
}
function sayHi(event) {
console.log('Hi!', this, event.type);
}
// Start
const debounced = debounce(sayHi, 500);
window.addEventListener('resize', debounced);
document.body.addEventListener('click', debounced)
{
"name": "vanilla-debounce",
"version": "0.0.0"
}
'use strict';
// Vanilla Debounce implementation
function debounce(func) {
var wait = arguments.length <= 1 || arguments[1] === undefined ? 100 : arguments[1];
var timeout = void 0;
return function () {
var _this = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
clearTimeout(timeout);
timeout = setTimeout(function () {
func.apply(_this, args);
}, wait);
};
}
function sayHi(event) {
console.log('Hi!', this, event.type);
}
// Start
var debounced = debounce(sayHi, 500);
window.addEventListener('resize', debounced);
document.body.addEventListener('click', debounced);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment