mojuba
mojuba

Reputation: 12227

Implementing a setTimeout() wrapper as a method in Element.prototype

I'm trying to add a method to Element.prototype that would call the user function with the same this as the current object, via the system setTimeout(). My implementation looks as follows:

Element.prototype.timeout =
    function (func, delay)
    {
        var that = this;
        return setTimeout(function () { func.call(that) }, delay);
    }

Is there a more efficient or elegant way of doing this?

(no jQuery please)

Upvotes: 0

Views: 1477

Answers (2)

np42
np42

Reputation: 947

If you really want to avoid lambda function, you can do something like:

Function.prototype.delay = function (delay, context) {
  this.self = context;
  this.args = Array.prototype.slice.call(arguments, 2);
  return setTimeout(this, delay);
};

(function () {
  var self = arguments.callee.self || this;
  var args = arguments.callee.args || Array.prototype.slice.call(arguments);
  alert(args[0]);
}).delay(1500, null, 42);

But it's quite ugly to do that.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707876

The only other thing I can think of it to just make it a utility function like this that you could use with any function or method on any object:

function delayMethod(obj, method, delay) {
    setTimeout(function() {
        method.call(obj);
    }, delay);
}

or, a bit more extensible with a variable number of arguments:

function delayMethod(obj, method, delay /* args to method go here */) {
    var args = [].slice.call(arguments, 3);
    setTimeout(function() {
        method.apply(obj, args);
    }, delay);
}

Upvotes: 0

Related Questions