Nick Riggs, Web Developer

Making stuff up about web development since last week.

7 September 2010

Subscribe to our RSS feed

Posted in JavaScript July 23, 2009

Create a prototype function to make delaying function execution more readable

The more involved I get with Html5 applications, the more JavaScript’s setTimeout function finds its way into my code. The syntax has gotten annoying to me because it doesn’t really say what I’m doing. It sounds like I’m setting the timeout of an AJAX request instead of delaying the execution of code. Furthermore, I almost never use it to evaluate a string of code; instead I use to delay a function call, such as:

var addStuff = function(x, y) {
    window.alert(x + y);
}

setTimeout(function() { addStuff(10, 5); }, 1000);

So I decide to add a delay() prototype function to make for more readable code, here is the implementation:

Function.prototype.delay = function(wait) {
    var thisFunction = this;
    var thisArgs = new Array();

    for (var index = 1; index != arguments.length; index++)
        thisArgs.push(arguments[index]);

    window.setTimeout(function() {
        thisFunction.apply(thisFunction, thisArgs);
    }, wait);
};

Using the delay() function now makes for more implicit code:

addStuff.delay(1000, 10, 5);

Or inline with the function declaration:

(function(x, y) { window.alert(x + y); }).delay(1000, 10, 6);