Skip to content

Instantly share code, notes, and snippets.

@peduarte
Last active February 18, 2021 21:35
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peduarte/969217eac456538789e8fac8f45143b4 to your computer and use it in GitHub Desktop.
Save peduarte/969217eac456538789e8fac8f45143b4 to your computer and use it in GitHub Desktop.
Vanilla Throttle
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ESNextbin Sketch</title>
<!-- put additional styles and scripts here -->
</head>
<body>
<!-- put markup and other contents here -->
</body>
</html>
// Vanilla Throttle implementation
function throttle(func, wait = 100) {
let timer = null;
return function(...args) {
if (timer === null) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, wait);
}
};
}
function sayHi(event) {
console.log('Hi!', this, event.type);
}
// Start
const throttled = throttle(sayHi, 500);
window.addEventListener('resize', throttled);
document.body.addEventListener('click', throttled)
{
"name": "esnextbin-sketch",
"version": "0.0.0"
}
'use strict';
// Vanilla Throttle implementation
function throttle(func) {
var wait = arguments.length <= 1 || arguments[1] === undefined ? 100 : arguments[1];
var timer = null;
return function () {
var _this = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (timer === null) {
timer = setTimeout(function () {
func.apply(_this, args);
timer = null;
}, wait);
}
};
}
function sayHi(event) {
console.log('Hi!', this, event.type);
}
// Start
var throttled = throttle(sayHi, 500);
window.addEventListener('resize', throttled);
document.body.addEventListener('click', throttled);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment