Created
July 21, 2012 15:20
-
-
Save icio/3156122 to your computer and use it in GitHub Desktop.
delay.js
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
var _log_start = Date.now(); | |
/** | |
* Helper for logging which prepends a time-offset | |
*/ | |
function log() | |
{ | |
console.log.apply(console, ["["+(Date.now()-_log_start)+"]"].concat(args(arguments))); | |
} | |
/** | |
* Helper for converting `arguments` object in functions into an Array | |
* @param {arguments} argu | |
* @return {Array} | |
*/ | |
function args(argu) | |
{ | |
var args = []; | |
for (var i = 0; i < argu.length; i++) | |
args.push(argu[i.toString()]); | |
return args; | |
} | |
/** | |
* A wrapper for delaying calls to functions. | |
* @param {function} fn The function to be called after the delay | |
* @param {integer} timeout The delay timeout | |
* @param {object} obj [optional] The object that the function is called on | |
*/ | |
function delay(fn, timeout, obj) | |
{ | |
if (obj && typeof fn == "string") | |
fn = obj[fn]; | |
return function() { | |
var argv = args(arguments); | |
setTimeout(function() { | |
fn.apply(obj || null, argv); | |
}, timeout); | |
} | |
} | |
/** | |
* This is our target function: the one that we want invoked upon a particular | |
* event occuring, such as a client connecting or a HTTP request completing. | |
*/ | |
function ding() | |
{ | |
log("Ding!"); | |
} | |
/** | |
* This is the entry function which will set up the event-triggering mechanisms. | |
* In this instance, there event is the function itself being fired, so we | |
* simply invoke the callback immediately. | |
*/ | |
function main() { | |
// Something will eventually happen, at which point we want to trigger the callback | |
ding(); | |
} | |
/* | |
* Here we optionally add in some delays | |
*/ | |
var arg = process.argv[2]; | |
if (arg == "debug") { | |
ding = delay(ding, 1000); | |
} | |
// GOGOGO | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment