Javascript – Passing parameters to a function called with setTimeout

I came across a need for the usage of setTimeout() as a delay for a mouse-over event (no need to have everything happen the instant something is moused) – and wanted to pass a parameter along to the function called – after the timer was actuated. The presumed method did not work – so I had to search around a bit. I thought I’d post my findings here as well…

 

[code]

 

<script type=”text/javascript”>

setTimeout(My_Function_To_Call_When_Timer_Is_Triggered, 2000); // Timer set to call function ” after two seconds – typical usage

 

function My_Function_To_Call_When_Timer_Is_Triggered( ){

alert(“timer called”);

}

</script>

 

[/code]

 

How about when you want to pass a parameter to the function? I thought It would be like this:

[code]

 

setTimeout(My_Function_To_Call_When_Timer_Is_Triggered(Pass_A_Parameter ), 2000); // <<< INCORRECT! Presumed method – Timer set to call function ” after two seconds – and pass a parameter to that function

 

setTimeout(My_Function_To_Call_When_Timer_Is_Triggered, 2000, “My Parameter String”); // <<< CORRECT!  Proper Method Timer set to call function ” after two seconds – and pass a parameter to that function

 

[/code]
[SHORTCODE_Insert_Google_Adsence_Here]
Continue reading “Javascript – Passing parameters to a function called with setTimeout”