Created
October 31, 2016 18:31
-
-
Save abhidilliwal/7d70c81fd652bfbb1f17d25c372e6a9d to your computer and use it in GitHub Desktop.
Throttle.js: rate limiter.
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
/** | |
* 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