Vanilla Debounce esnextbin
Last active
August 25, 2022 14:55
-
-
Save peduarte/7ee475dd0fae1940f857582ecbb9dc5f to your computer and use it in GitHub Desktop.
Vanilla Debounce
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
<!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> |
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
// 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) |
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
{ | |
"name": "vanilla-debounce", | |
"version": "0.0.0" | |
} |
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
'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