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
 
  1. // this code will call the "doSomething" in 2 seconds,    
  2. // but won't pass the "good" to it    
  3. 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
 
  1. /**   
  2.  * Net.Inluck.Common.js   
  3.  * code by chad@inluck.net   
  4.  * 2010   
  5.  */    
  6.      
  7. /**   
  8.  * returns a delegated function   
  9.  * @param f   
  10.  * @param params   
  11.  * @return   
  12.  */    
  13. function Inluck_Delegate(f,params)    
  14. {    
  15.     var args = Array.prototype.slice.call(arguments,1);    
  16.     var _f = function()    
  17.     {    
  18.         f.apply(null,args);    
  19.     }    
  20.     return _f;    
  21. }    


Here's a complete and simple example:

Code - XML/HTMLPlain Text
 
  1. <HTML>     
  2. <HEAD>     
  3. <TITLE>Pass parameters to setTimeout callback using function delegation in Javascript</TITLE>     
  4. <script type="text/javascript">     
  5. <!--     
  6. /**     
  7.  * Net.Inluck.Common.js     
  8.  * code by chad@inluck.net     
  9.  * 2010     
  10.  */     
  11.       
  12. /**     
  13.  * returns a delegated function     
  14.  * @param f     
  15.  * @param params     
  16.  * @return     
  17.  */     
  18. function Inluck_Delegate(f,params)     
  19. {     
  20.     var args = Array.prototype.slice.call(arguments,1);     
  21.     var _f = function()     
  22.     {     
  23.         f.apply(null,args);     
  24.     }     
  25.     return _f;     
  26. }     
  27. -->     
  28. </script>     
  29. <script type="text/javascript">     
  30. var timeoutForMsg = 2000;     
  31. function alertContent(id){     
  32.     alert(document.getElementById(id).value);     
  33. }     
  34. </script>     
  35. <HEAD>     
  36. <BODY>     
  37. <input type="text" id="txbContent" value="input something here..."/>     
  38. <input type="button" onclick="setTimeout(Inluck_Delegate(alertContent,'txbContent'),timeoutForMsg);" value="Alert Content in 2 seconds"/>     
  39. </BODY>     
  40. </HTML>    



References:
[1] http://hi.baidu.com/baozi52/blog/item/81a2c4f8f8ed6e03d8f9fdf0.html