The problem is in your setTimeout() call.

When you pass a string argument to setTimeout(), that string is evaluated
*in the global context*.

Instead, pass a function to setTimeout() and that function will be executed
in the scope you expect.

Since you're just calling a single function anyway, you can simply give its
name to setInterval():

setInterval( crossfade, 5000 );

Or you can pass a function expression to setInterval():

setInterval( function() {
    // body here
}, 5000 );

Also, just to make sure you know, this pattern you're using doesn't wait for
a "document ready" before executing the code:

    (function($) {
        // code here
    })(jQuery);

It executes the "code here" immediately where you place this function.
That's perfectly fine and may be what you want. If you want to wait for
document ready you can change it to:

    jQuery(function($) {
        // code here
     });

Or if you have some code you want to run immediately and other code that
should wait for document ready, you can combine the two approaches:

    (function($) {

        // code here runs immediately

        $(function() {
            // code here runs when document ready
            // and can access variables in outer function
        });

    })(jQuery);

-Mike

On Tue, Nov 24, 2009 at 9:31 AM, Magnificent <
imightbewrongbutidontthin...@gmail.com> wrote:

> Hello all,
>
> I'm trying to group some exisiting top-level functions inside a
> closure (to avoid polluting the global namespace) but I'm not quite
> getting it to work.
>
> First, all the JS works outside my anonymous function, but once I put
> it in the anonymous function I get an error of "crossfade is not
> defined".  Does anyone see anything completely obvious that I am
> missing?
>
> I'm not quite getting why the the setInterval/crossfade works outside
> the anonymous function but not inside.  Anything inside start() should
> be able to see vars/functions outside start() and it should all be
> protected in the closure created by the top-level anonymous function?
> I'm not trying to access anything *within* crossfade(), I'm just
> trying to execute it.
>
>
> (function($) {
>
>        //vars up here that internal functions can access
>        //also using some jquery inside here, so using $
>
>        function crossfade() {
>                //body here
>        }
>
>        //other functions
>
>        function start() {
>                //body here
>
>                cInterval = setInterval('crossfade()', 5000);
>        }
>
> })(jQuery);
>

Reply via email to