PDA

View Full Version : Resolved Help with variable passing



cr3ative
01-28-2005, 03:57 PM
Hi guys,

I have a total case of mental block today. This function recieves a variable, and then needs to set up a timer which calls another function, sending on that variable to the timered function.

With me?


function process(which2){
cleartimer()
setTimeout("fadeoutest(which2)",50)
}

I want it to pass the "which2" variable on to the fadeoutest function, but it doesn't seem to want to; script error messages.

I could do this:


function process(which2){
cleartimer()
var2=which2
setTimeout("fadeoutest(var2)",50)
}But it doesn't seem like a very good way to do it.

Is that the only workaround?
cr3ative

mwinter
01-28-2005, 06:05 PM
function process(which2){
cleartimer()
setTimeout("fadeoutest(which2)",50)
}Simple. :D


function process(which) {
cleartimer();
setTimeout(function() {fadeoutest(which);}, 50);
}The function expression passed to setTimeout forms a closure, preventing garbage collection of the outer argument, which. The comp.lang.javascript FAQ (http://jibbering.com/faq/) covers (in the notes) closures in detail (http://www.jibbering.com/faq/faq_notes/closures.html), including what I've presented above regarding the use of references with setTimeout (http://www.jibbering.com/faq/faq_notes/misc.html#mtSetTI). However, the explanation of the former is very detailed so if you want a gentler introduction into the specifics, just ask. :)



function process(which2){
cleartimer()
var2=which2
setTimeout("fadeoutest(var2)",50)
}But it doesn't seem like a very good way to do it.As the latter article I cited states (I've assumed you've read it now), obsolete browsers don't support references as arguments to setTimeout. In this case, you'd have to provide global access to the function expression. The toString method assigned to the function expression could then call the function object via this global. However, if calls to process can occur in rapid succession, things start becoming more complicated (but still feasible). I won't bother explaining this unless you say it'll be necessary.

Hope that's some food for thought,
Mike

cr3ative
01-28-2005, 06:08 PM
Cheers Mike - this should help a lot in my project.

cr3ative

jlizarraga
12-13-2008, 05:26 AM
lol, this old post just totally helped me.

jlizarraga
12-13-2008, 05:30 AM
Wow, that's a lot of views. Not surprising considering how I found it:

http://www.google.com/search?q=pass+variable+settimeout