Chad 2010-05-10
In special cases, you might want to pass parameters to the callback of the "setTimeout" javascript function. I tried the following code, but that doesn't work at all:
Code - JavaScriptPlain Text
- // this code will call the "doSomething" in 2 seconds,
- // but won't pass the "good" to it
- setTimeout("doSomething('good')",2000);
Then I wonder if we can use function delegation in Javascript. After some search, I found something useful[1] and made it into the following code, which works fine :
Code - JavaScriptPlain Text
- /**
- * Net.Inluck.Common.js
- * code by chad@inluck.net
- * 2010
- */
- /**
- * returns a delegated function
- * @param f
- * @param params
- * @return
- */
- function Inluck_Delegate(f,params)
- {
- var args = Array.prototype.slice.call(arguments,1);
- var _f = function()
- {
- f.apply(null,args);
- }
- return _f;
- }
Here's a complete and simple example:
Code - XML/HTMLPlain Text
- <HTML>
- <HEAD>
- <TITLE>Pass parameters to setTimeout callback using function delegation in Javascript</TITLE>
- <script type="text/javascript">
- <!--
- /**
- * Net.Inluck.Common.js
- * code by chad@inluck.net
- * 2010
- */
- /**
- * returns a delegated function
- * @param f
- * @param params
- * @return
- */
- function Inluck_Delegate(f,params)
- {
- var args = Array.prototype.slice.call(arguments,1);
- var _f = function()
- {
- f.apply(null,args);
- }
- return _f;
- }
- -->
- </script>
- <script type="text/javascript">
- var timeoutForMsg = 2000;
- function alertContent(id){
- alert(document.getElementById(id).value);
- }
- </script>
- <HEAD>
- <BODY>
- <input type="text" id="txbContent" value="input something here..."/>
- <input type="button" onclick="setTimeout(Inluck_Delegate(alertContent,'txbContent'),timeoutForMsg);" value="Alert Content in 2 seconds"/>
- </BODY>
- </HTML>
References:
[1] http://hi.baidu.com/baozi52/blog/item/81a2c4f8f8ed6e03d8f9fdf0.html