1

I want to pass id1, id2 and id3 through the function below. This works just fine:

function doSomething(id1,id2,id3) {
    $(id1).fadeIn('slow',.25);
    $(id1).fadeIn('slow',.25);
    $(id1).fadeIn('slow',.25);
};

But this does not work:

function doSomething(id1,id2,id3) {
    setTimeout( " $(id1).fadeIn('slow',.25) ", 300);
    setTimeout( " $(id1).fadeIn('slow',.25) ", 300);
    setTimeout( " $(id1).fadeIn('slow',.25) ", 300);
};

How do I get the second one to work? My thought is I need some punctuation around the id's. Or perhaps I can set a variable for the function within the setTimeout brackets. Any ideas?

0

2 Answers 2

5

It's bad practice to get setTimeout() to evaluate a string. Instead, use an anonymous function:

function doSomething(id1, id2, id3) {
    setTimeout(function() {
        $(id1).fadeIn('slow', 0.25);
        $(id2).fadeIn('slow', 0.25);
        $(id1).fadeIn('slow', 0.25);
    }, 300);
};

Note that I've put all your fadeIn()s into one setTimeout(); it does the same thing as all your timeouts will trigger at the same time (300ms). If you IDs are strings, you could do this too:

function doSomething(id1, id2, id3) {
    setTimeout(function() {
        $(id1 + ', ' + id2 + ', ' + id3).fadeIn('slow', 0.25);
    }, 300);
};

Although it's a little messy, but $.add() might do the trick.

3

setTimeout accepts a function callback and a timeout. By wrapping your function call in quotes, you're passing it a string. Try this:

function doSomething(id1,id2,id3) {
    setTimeout( function() { 
       $(id1).fadeIn('slow',.25);
       $(id2).fadeIn('slow',.25);
       $(id3).fadeIn('slow',.25); 
    }, 300);
};

EDIT: As @nnnnnn pointed out, a string can be passed but it is a bad idea. Essentially, when you pass in a string it is called with the privileges of the caller and thus will not have access to the scope variables within "doSomething" but a completely different scope.

1
  • 1
    Passing a string to setTimeout isn't inherently wrong - it is certainly valid syntax. The problem with the string syntax is the code in the string won't run in the right scope to make use of the local id1 and other parameters, something that your code fixes.
    – nnnnnn
    Jan 7, 2012 at 2:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.