Javascript – Passing Parameters for the Function in setTimeout()

Previous post: Javacript – Schedule a Function call by setTimeout()

If the delayed function has input parameters, setTimeout() would fail when you simply add the parameters in the setTimeout() call.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    /* The call will fail and the alert box will display immediately */
    setTimeout(delayedAlert("Hi Eureka!"), 3000);
  });

  function delayedAlert(str) {
    alert(str);
  }
</script>


 

The following piece of code is the proper way to pass the input parameters to the function in setTimeout().

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    /* It works now. =) */
    setTimeout(function(){delayedAlert("Hi Eureka!")}, 3000);
  });

  function delayedAlert(str) {
    alert(str);
  }
</script>

 

Done =)

Reference: Passing parameters to a function called with setTimeout

One thought on “Javascript – Passing Parameters for the Function in setTimeout()”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.