PDA

View Full Version : Using a function as a parameter of another one



ellyz
12-27-2005, 11:34 AM
hi everyone,
I think my question should be simple, but I'm just not too falmiliar with all syntax tricks. I'd like to call a function hide(id) in the setTimeout() function, but hide has it's own params - (id) - and once inside setTimeout, id becomes undefinied.. Here's the example, to make myself clear:


function show(id, file) {
document.getElementById(id).src = file;
setTimeout("hide(id)", 1000);
}

there should be a way to put a parametered function inside setTimeout, no? :confused: cuz actually all examples I could find were like setTimeout("hide()", 1000), hide being empty...
oh, and here's the hide() function just in case:

function hide(id){
document.getElementById(id).src = 'back.gif';
}

thanks for your help!!

ddadmin
12-27-2005, 12:47 PM
You can certainly pass a parameter into a function being called by setTimeout(). In this case:


function show(id, file) {
document.getElementById(id).src = file;
setTimeout("hide('test')", 1000);
}

This assumes that "test" is the ID of the element you wish to "hide."

jscheuer1
12-27-2005, 06:45 PM
Yes but, it gets tricky when using a parameter of the function that is setting the timeout as a parameter of the function set by the timeout. Think about it. :)

The problem is that the original function's parameter is a local variable or something like one. However, by the time the timeout fires, it is looking for its value in the global scope. This can be overcome by passing the original parameter as a local variable written to the timeout call as a literal:


function show(id, file) {
document.getElementById(id).src = file;
setTimeout("hide("+id+")", 1000);
}

or sometimes:


function show(id, file) {
document.getElementById(id).src = file;
setTimeout("hide('"+id+"')", 1000);
}

can be required.

ddadmin
12-27-2005, 10:20 PM
John is right, ignore my solution ellyz, I didn't notice that "id" is passed in as a parameter of show(). In that case John's second example would work:


<img id="test" src="photo1.jpg" />

<script type="text/javascript">

function show(id, file) {
document.getElementById(id).src = file;
setTimeout("hide('"+id+"')", 1000);
}

function hide(id){
document.getElementById(id).src = 'photo3.jpg';
}

show("test", "photo2.jpg")

</script>
Thanks for catching that John. :)