Vanilla Throttle esnextbin
Last active
February 18, 2021 21:35
-
-
Save peduarte/969217eac456538789e8fac8f45143b4 to your computer and use it in GitHub Desktop.
Vanilla Throttle
This file contains 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>ESNextbin Sketch</title> | |
<!-- put additional styles and scripts here --> | |
</head> | |
<body> | |
<!-- put markup and other contents here --> | |
</body> | |
</html> |
This file contains 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 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) |
This file contains 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": "esnextbin-sketch", | |
"version": "0.0.0" | |
} |
This file contains 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 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