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! :)

Tags: ,

4 Responses to “Javascript – Passing Multiple Parameters through setTimeout”

  1. harald

    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?

  2. Richard

    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.

  3. Richard

    THIS IS JUST AWESOME! THANKS!!!

  4. Richard

    @Richard, Thanks!

Leave a Reply