Using params with setTimeOut

/ Published in: JavaScript
Save to your folder(s)

With setTimeOut a reference to a function object cannot provide parameters for the scheduled execution of that function.
We can instead use a closure to provide parameters for the execution of a function prior to the execution of that function.

Copy this code and paste it in your HTML
  1. function callLater(paramA, paramB, paramC){
  2. /* Return a reference to an anonymous inner function created
  3.   with a function expression:-
  4.   */
  5. return (function(){
  6. /* This inner function is to be executed with - setTimeout
  7.   - and when it is executed it can read, and act upon, the
  8.   parameters passed to the outer function:-
  9.   */
  10. paramA[paramB] = paramC;
  11. });
  12. }
  14. ...
  16. /* Call the function that will return a reference to the inner function
  17.   object created in its execution context. Passing the parameters that
  18.   the inner function will use when it is eventually executed as
  19.   arguments to the outer function. The returned reference to the inner
  20.   function object is assigned to a local variable:-
  21. */
  22. var functRef = callLater(elStyle, "display", "none");
  23. /* Call the setTimeout function, passing the reference to the inner
  24.   function assigned to the - functRef - variable as the first argument:-
  25. */
  26. hideMenu=setTimeout(functRef, 500);


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.