One of the nice prototype functions available in the Prototype JS library is Function.prototype.delay(). The reason this is a great function is the fact that it actually allows you to call a function after a certain amount of time with the specified parameters. The following is an example of how to use this function:

function showMsg(msg) {
  alert(msg);
}

// In five seconds, show the appropriate message.
var timeoutID = showMsg.delay(5, "Five seconds have passed.");

So without looking at the code, how can we get this to work? If we already are using a library such as jPaq which supplies the Function.prototype.curry() function, we could use the following:

Function.prototype.delay = function(seconds) {
  // Remove the seconds from the parameters to pass the this function.
  var args = [].slice.call(arguments, 1);
  // Call this function with the specified parameters in the specified amount
  // of seconds.
  return setTimeout(this.curry.apply(this, args), seconds * 1000);
};

What if Function.prototype.curry() is not already available to us? In that case, we can use the following:

Function.prototype.delay = function(seconds) {
  // Remove the seconds from the parameters to pass the this function.
  var args = [].slice.call(arguments, 1);
  // Call this function with the specified parameters in the specified amount
  // of seconds.
  var fnThis = this;
  return setTimeout(function() {
    fnThis.apply(undefined, args);
  }, seconds * 1000);
};

As you can see, implementing this function is pretty easy, even if we cannot rely on the existence of another JavaScript library.

Categories: BlogJavaScript

1 Comment

Chris West's Blog » JavaScript – Prototype's delay() Function · August 11, 2011 at 6:49 PM

[…] G&#959 here t&#959 see th&#1077 original: Chris West's Blog » JavaScript – Prototype's delay() Function […]

Leave a Reply

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