Last active
December 21, 2015 09:28
-
-
Save RadGH/6284881 to your computer and use it in GitHub Desktop.
This is a simple JavaScript rate limiter that you can stick in any function
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
// This script prevents a function from running too frequently. | |
// Pick one of these three variations, then copy the code to a function of your choice. Do not copy the entire script. | |
// VARIATION A: Simply ignore any excessive function calls | |
// VARIATION B: Ignore excessive function calls, but call the function again once the limiter has expired. Ignore parameters. | |
// VARIATION C: Like variation B, call the function after limiter expired - but pass in function's parameters. | |
// Variation A ---------------- | |
// Replace 150 with the rate limit amount of your choice. | |
if ( typeof this.lastCalled == 'undefined' ) this.lastCalled = 0; | |
var timestamp = new Date().getTime(); | |
if ( this.lastCalled > timestamp - 150 ) { | |
return false; | |
}else{ | |
this.lastCalled = timestamp; | |
} | |
// Varibation B --------------- | |
// Replace 150 (used twice) with the rate limit amount of your choice. | |
// Replace ENTER_FUNCTIO_NAME with the name of your function. | |
// Note: If parameters are being passed in to the function, you will want variation C. | |
if ( typeof this.lastCalled == 'undefined' ) { | |
this.lastCalled = 0; | |
this.timeout = false; | |
} | |
var timestamp = new Date().getTime(); | |
if ( this.lastCalled > timestamp - 150 ) { | |
if ( this.timeout == false ) this.timeout = setTimeout( ENTER_FUNCTION_NAME, 150 ); | |
return false; | |
}else{ | |
this.timeout = false; | |
this.lastCalled = timestamp; | |
} | |
// Variation C: | |
// Replace 150 (used twice) with the rate limit amount of your choice. | |
// Replace ENTER_FUNCTION_NAME with the name of your function | |
// Replace ENTER_PARAMETER with your parameter(s) | |
// This code is untested, the closure is probably incorrect within the setTimeout function. But it will get you started. | |
if ( typeof this.lastCalled == 'undefined' ) { | |
this.lastCalled = 0; | |
this.timeout = false; | |
} | |
var timestamp = new Date().getTime(); | |
if ( this.lastCalled > timestamp - 150 ) { | |
if ( this.timeout != false ) clearTimeout( this.timeout ); | |
this.timeout = setTimeout( function() { ENTER_FUNCTION_NAME( ENTER_PARAMETER ); }, 150 ); | |
return false; // Function was called within 150ms of a previous call, ignore | |
}else{ | |
this.timeout = false; | |
this.lastCalled = timestamp; // Function is OK to run, remember the timestamp for next time | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment