Add

Javascript – Passing Multiple Parameters through setTimeout

One of the problems that I’ve faced with Javascript is passing multiple parameters through the setTimeout function. I found this little snippet on the internet a few months ago and would like to share it with you. I don’t know who the original author is so I could not give him/her proper credit. Thanks!

var _st = window.setTimeout;

window.setTimeout = function(fRef, mDelay) { 
	if(typeof fRef == "function") {  
		var argu = Array.prototype.slice.call(arguments,2); 
		var f = (function(){ fRef.apply(null, argu); }); 
		return _st(f, mDelay); 
	} 
	return _st(fRef,mDelay);
}

Define your function to call with setTimeout:

function alertMe(message, name) {
    alert(message + name);
}

Now, just call the function.

var message = 'Hello, ';
var name = 'Richard';
setTimeout(alertMe, 2000, message, name);

Hope this helps someone! :)

The Discussion

see what everyone is saying

  • harald June 24th, 2009 at 1:51 am #1

    why would anyone like to overwrite the setTimeout method, when it’s so much easier to just write:

    var message = ‘Hello’;
    var name = ‘Richard’;

    window.setTimeout(function() { alertMe(message, name); }, 2000);

    … am i missing something or did the original author of the snippet did not understand variable scope in javascript?

  • Richard June 28th, 2009 at 5:40 pm #2

    Hello Harald! Thank you for your comment. Sometimes it may be necessary to override native functions to add additional functionality or to implement something specific to your requirements. Your example is missing one major element that this post contains. The ability to pass multiple parameters to a function that is called in setTimeout at the specified interval. With the native setTimeout this is not possible.

  • Richard October 30th, 2009 at 6:45 pm #3

    THIS IS JUST AWESOME! THANKS!!!

  • Richard November 1st, 2009 at 9:27 pm #4

    @Richard, Thanks!

Respond

get in on the action.

Are you Human?
 

* Required

Random Posts Recent Comments Tags

  • Richard Says:

    @prits, Check your settings for the URL and clear the Magento cache....

  • Richard Says:

    @hucks, That should work....

  • Richard Says:

    @Tony, I believe it is possible. There is only 1 way to find out and that's to give it a try. Go th...

  • Richard Says:

    @Nexus Rex, Sure, just add this class to the field: class="required-entry input-text"...

  • Richard Says:

    @Kalamingo, Sure read this comment (http://www.richardcastera.com/2009/05/21/magento-display-new-pr...

Page optimized by WP Minify