Clean Up the setTimeout Function

Published on Author nickriggs1 Comment

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);

One Response to Clean Up the setTimeout Function

Leave a Reply

Your email address will not be published. Required fields are marked *