Jump to content

Passing parameters into function.


atar.yosef

Recommended Posts

Hi there!!Just wanted to know please, if this is possible to pass A VARIABLE as parameters into a function that is called by the 'setTimeout' function, for example;setTimeout("myFunction(myParameter)", 1000);I tried to do so but with no success. Can anyone help me?Thanks in advance!!Atar.

Link to comment
Share on other sites

You would pass in the parameters for the function after the delay parameter.. for example: var timeOut = setTimeout(myFunction, delay, param1, param2); For the parameter for the function, best to call the function by reference without any quotes(instead of as a string).

Edited by Don E
Link to comment
Share on other sites

var timeOut = setTimeout(myFunction, this is the delay parameter, param1, param2); You would set that whatever delay of time you want before calling the function. To call function by reference, call it with no quotes and parenthesis. Here's a full example:

<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Set Time out</title><script type="text/javascript">var timeOut;     function setGreet()     {          timeOut = setTimeout(sayGreet, 3000, "Hello", "There!"); //waits 5 seconds before calling function sayGreet()      }      function sayGreet(greet1, greet2)     {           alert(greet1 + " " + greet2);           clearTimeout(timeOut);     } </script></head> <body> <button type="button" onClick="setGreet();">Say Hello!</button></body></html>

Edited by Don E
Link to comment
Share on other sites

In place of the string literals, you can have the variables there instead, but to be on the safe side, in case it doesn't work in older browsers, go with the example smiles gave. However, the example I gave you works.. according to testing it.. in up to date browsers(except IE ;) )

Edited by Don E
Link to comment
Share on other sites

IE's a pretty big part of the browser community to leave out, but I agree that smiles' example is the way to go. again, just replace the string literals with your desired variables.

Edited by thescientist
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...