Skip to content

Instantly share code, notes, and snippets.

@abhidilliwal
Created October 31, 2016 18:31
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 abhidilliwal/7d70c81fd652bfbb1f17d25c372e6a9d to your computer and use it in GitHub Desktop.
Save abhidilliwal/7d70c81fd652bfbb1f17d25c372e6a9d to your computer and use it in GitHub Desktop.
Throttle.js: rate limiter.
/**
* Throttle function
*
* Runs the `func` without any delay when called normally
* but if called many times it will rate limit.
*/
function throttle (func, wait) {
var t;
var firstTime = true;
return function () {
var args = arguments;
var othis = this;
var didItRunAlready = false;
if (firstTime) {
func.apply(othis, args);
didItRunAlready = true;
firstTime = false;
}
clearTimeout(t);
t = setTimeout(function () {
if (!didItRunAlready) {
func.apply(othis, args);
}
firstTime = true;
}, wait);
}
}
/////////////// USAGE //////////////////
// example function
function showMessage(e) {
console.log("showing message... ", Math.random());
console.log("this ", this);
}
// html: <button id="btn">write something</button>
// usage
document.getElementById("btn").addEventListener("click", throttle(showMessage, 200));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment