Created
December 15, 2012 02:35
-
-
Save IceCreamYou/4290839 to your computer and use it in GitHub Desktop.
A JavaScript function to log messages to the console periodically.
This file contains hidden or 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
/** | |
* Periodically log a message to the JavaScript console. | |
* | |
* This is useful for logging things in loops; it avoids being overwhelmed by | |
* an unstoppable barrage of similar log messages. Example calls: | |
* | |
* # Log "message" to the console no more than every 500ms. | |
* logPeriodically('message', 500); | |
* # Log "message" as an error no more than every 500ms. | |
* logPeriodically('message', 500, console.error); | |
* # Provide an ID if you want to keep track of multiple logging calls. | |
* logPeriodically('draw message', 500, 'draw'); | |
* logPeriodically('update message', 500, 'update'); | |
* # You can also provide both an ID and a logging function. | |
* logPeriodically('draw message', 500, 'draw', console.error); | |
* logPeriodically('update message', 500, 'update', console.log); | |
* | |
* @param ... | |
* An arbitrary number of arguments to pass to the loggging function. | |
* @param freq | |
* The minimum amount of time in milliseconds that must pass between messages | |
* with the same identifier before logging the next one. To only log | |
* something once, pass Infinity to this parameter. | |
* @param id | |
* (Optional) An identifier for the log message. Log messages with the same | |
* identifier will be logged no more often than the amount of time specified | |
* by the freq parameter. | |
* @param func | |
* (Optional) The logging function to use. Defaults to console.log. | |
*/ | |
function logPeriodically() { | |
if (arguments.length < 2) { | |
return; | |
} | |
var freq = 0, id = '_', func = Array.prototype.pop.call(arguments); | |
if (typeof func == 'number') { | |
freq = func; | |
func = console.log || function() {}; | |
} | |
else if (typeof func == 'string') { | |
freq = Array.prototype.pop.call(arguments); | |
id = func; | |
func = console.log || function() {}; | |
} | |
else if (typeof func == 'function') { | |
id = Array.prototype.pop.call(arguments); | |
if (typeof id == 'string') { | |
freq = Array.prototype.pop.call(arguments); | |
} | |
else if (typeof id == 'number') { | |
freq = id; | |
id = '_'; | |
} | |
} | |
if (typeof this.lastLogged == 'undefined') { | |
this.lastLogged = {}; | |
} | |
if (typeof this.lastLogged[id] == 'undefined') { | |
this.lastLogged[id] = 0; | |
} | |
var now = Date.now(); | |
if (now > this.lastLogged[id] + freq) { | |
this.lastLogged[id] = now; | |
func.apply(func, arguments); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment