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! 
why would anyone like to...
why would anyone like to overwrite the setTimeout method, when it's so much easier to just write:
... am i missing something or did the original author of the snippet did not understand variable scope in javascript?Hello Harald! Thank you for...
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.
His solution does in fact...
His solution does in fact provide the functionality you describe while also avoiding overwriting native functionality... by using native functionality.
Native setTimeout + closure will be more efficient than any solution that involves array manipulation.
THIS IS JUST AWESOME!...
THIS IS JUST AWESOME! THANKS!!!
Thanks!...
Thanks!
Thanks a lot !!! I was...
Thanks a lot !!!
I was looking for passing multiple args to setTimeout for hours. Now, it's works !!!
Wow dude. You saved me from...
Wow dude. You saved me from having a lot of headaches. Thanks!
Thanks!...
Thanks!
Hi Richard, thanks for...
Hi Richard, thanks for sharing the code. It looks nice, but I think the following code can do this job easier. Don't you think?
Thanx so much Richard! Your...
Thanx so much Richard! Your solution is fantastic!
Post new comment