Skip to content

Instantly share code, notes, and snippets.

@icio
Created July 21, 2012 15:20
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 icio/3156122 to your computer and use it in GitHub Desktop.
Save icio/3156122 to your computer and use it in GitHub Desktop.
delay.js
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